python 连接 mysql 数据库使用的是python中的 MySQLdb 模块
使用该模块前需要安装
可以使用源码安装也可以使用pip安装 或者使用ubuntu的apt-get 进行安装.
这里不做介绍
操作数据库涉及四个基本的操作
增删改查
关于数据库的操作可以自行查找相关资料
MySQLdb 模块的使用方法如下:
import MySQLdb
#创建数据库连接
conn = MySQLdb.connect(host="127.0.0.1",user="root",passwd="123123",db="testdb",chatset="utf8")
cu = conn.cursor()
# 设置查询语句
selectSQL = "select * from user"
selectResult = cu.execute(selectSQL)
#设置插入语句
insertSQL = "insert INTO user(name,group) VALUES(%s,%s)"
insertDate = [("user01","dba"),("user02","mgr"),("user03","staff")]
insertResult = cu.execute(selectSQL)
#设置更新语句
updateSQl = "update user set name=%s where NAME =%s"
updateData = ("newuser","user03")
updateResult = cu.execute(selectSQL)
#设置删除语句
delSQl = "delete from user WHERE name=%s"
delData = ("newuser")
delResult = cu.execute(selectSQL)
print cu.fetchall()
conn.commit()
cu.close()
conn.close()在使用中需要注意几个问题
MySQLdb.connect 的参数很多,这里只是涉及了常用的,通过看源码可以看其他参数
fetch有三种情况
fetchone() # 返回一条结果行
fetchmany(size=None) # 接收size条返回结果行
fetchall() # 接收全部的返回结果行
关于commit功能 autocommit 默认没有打开,所以如果使用的是,支持事务的存储引擎的时候,每次执行完事务后,需要手动commit,否则数据不会写入数据库.
参考
http://www.cnblogs.com/wupeiqi/articles/5095821.html
本文出自 “Will的笔记” 博客,请务必保留此出处http://timesnotes.blog.51cto.com/1079212/1735508
原文:http://timesnotes.blog.51cto.com/1079212/1735508