简介
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()
#关闭数据库连接