簡介
Python 標準數據庫接口爲 Python DB-API,Python DB-API爲開發人員提供了數據庫應用編程接口。
對應Mysql數據庫的接口是MySQLdb。
使用流程
- import API模塊
- 連接數據庫
- 執行sql語句,進行各種操作(查詢,插入,更新,刪除等)
- 關閉數據庫連接
實例
-
查詢
import MySQLdb
try:
db=connect_db()
cur=db.cursor()
table="_user"
sql="SELECT * FROM %s WHERE id = %d" % (table,user_id)
cur.execute(sql)
result=cur.fetchone()
cur.close()
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
db.close()
return result
fetchone(): 該方法獲取下一個查詢結果集。結果集是一個對象(用索引獲取字段值).
fetchall():接收全部的返回結果行.;例pepple_join=[]
result=cur.fetchall()
for row in result:
user_id=row[0]
user=query_user_byid(user_id)
people_join.append(user[4]) #索引到name字段
print people_join
cur.close()
- 插入
#連接數據庫如上例
sql="replace into %s (userId,permission) VALUES ('%s','%s')" % (table,user_id,state)
cur.execute(sql)
cur.close()
#若執行修改數據庫操作,要提交事務即執行commit()方法
db.commit()
#關閉數據庫連接