1、安装mysql-python驱动模块
1、pip install mysql-python
2、如果你使用的默认安装的python也可以使用 yum 安装 MySQL-python
yum install MySQL-python
如果你要在linux 下开发python程序要安装一下开发包。否则可以忽略。
yum install python-devel mysql-devel zlib-devel openssl-devel
3、windows下直接去pypi官网下载exe文件即可:
目前官网只有32位的mysql-python.exe驱动,地址:https://pypi.org/project/MySQL-python/,中下载MySQL-python-1.2.5.win32-py2.7.exe 。
http://www.codegood.com/archives/129 此地址 中32位和64位驱动均可下载。
2、初始化连接
模块引入之后我们就需要和数据库进行连接了,实例代码如下:
import MySQLdb
db = MySQLdb.connect(“127.0.0.1”,”root","123456","myciti" )
db = MySQLdb.connect(host="192.168.1.155", user="root", passwd="haha", db="test",charset="utf8")
数据库连接对事务操作的方法:commit() 提交 rollback() 回滚
详细参数:
host,连接的数据库服务器主机名,默认为本地主机(localhost)。
user,连接数据库的用户名,默认为当前用户。
passwd,连接密码,没有默认值。
db,连接的数据库名,没有默认值。
charset,连接字符集
conv,将文字映射到Python类型的字典。默认为MySQLdb.converters.conversions
cursorclass,cursor()使用的种类,默认值为MySQLdb.cursors.Cursor。
compress,启用协议压缩功能。
named_pipe,在windows中,与一个命名管道相连接。
init_command,一旦连接建立,就为数据库服务器指定一条语句来运行。
read_default_file,使用指定的MySQL配置文件。
read_default_group,读取的默认组。
unix_socket,在unix中,连接使用的套接字,默认使用TCP。
port,指定数据库服务器的连接端口,默认是3306
3、操作实例
#新增数据:
cursorAdd = dbAdd.cursor()
sql = "INSERT into t_user (name,address,phone) VALUES('%s','%s','%s');" % ("you","BJ","1222222")
print(cursorAdd.execute(sql))
dbAdd.commit()
dbAdd.close()
#删除数据:
cursorDel = dbDel.cursor()
sql = "delete from t_user where id=10;"
cursorDel.execute(sql)
dbDel.commit()
dbDel.close()
#修改数据:
cursorUpdate = dbUpdate.cursor()
sql = "update t_user set address='%s' where address='BJ';"%"BJJ"
cursorUpdate.execute(sql)
#dbUpdate.rollback()
dbUpdate.commit()
dbUpdate.close
cursor.execute(sql):返回执行后影响的行数。
#查询结果集:cursorSearch = dbSearch.cursor()
sql = "select * from t_user;"
cursorSearch.execute(sql)
data = cursorSearch.fetchall()
#data = cursorSearch.fetchone()
print cursorSearch.rowcount
for d in data:
print d
print d[2].encode("utf-8")