Python操作MySQL数据库


MySQL一直是我最爱的数据库,用Java编程时经常对MySQL进行操作。最近在学习Python,也想用Python操作一下MySQL数据库。
 首先当然是安装Python和MySQL,本人是python2.7,然后是安装MySQLdb,它就相当 于用Java连接数据库时的那个驱动一样,如果是ubuntu可直接使用命令
 
sudo apt-get install python-mysqldb

即可安装
 
如果是windows则可进去http://www.codegood.com/downloads下载相应版本的MySQLdb,下载完成后直接安装即可。
 
创建一个数据库:
 
Python代码 
#coding=utf-8 
 
import MySQLdb 
 
#建立和数据库系统的连接 
conn = MySQLdb.connect(host='localhost', user='root', passwd='root', db='test') 
 
#获取操作游标 
cursor = conn.cursor() 
#执行SQL,创建一个数据库 
cursor.execute("""create database python;""") 
 
#关闭连接,释放资源 
cursor.close() 
 
 
插入,修改数据:
 
 
Python代码 
# -*- coding: utf-8 -*- 
 
import MySQLdb 
 
conn = MySQLdb.connect(host='localhost', user='root', passwd='root') 
 
cursor = conn.cursor() 
 
#cursor.execute("""create database if not exists python""") 
 
#选择数据库 
conn.select_db('python') 
 
#执行SQL,创建一个数据表 
cursor.execute("""create table test(id int, info varchar(100)) """) 
 
value = [1,"我是中文,会不会乱码呢?"] 
 
#插入一条记录 
cursor.execute("insert into test values(%s, %s)", value) 
 
values = [] 
 
#生成插入参数值 
for i in range(20): 
    values.append((i, 'Hello mysqldb, I am recoder ' + str(i))) 
 
#插入多条记录 
cursor.executemany("""insert into test values(%s, %s) """, values) 
 
#修改记录 
cursor.execute("""update test set info='asdl;kfjalfkj' where id=3;""") 
cursor.close() 
 
 
上面的代码不知道为什么在windows下插入不了,但却不报错。但Linux下却非常正常。
 
 
MySQL的乱码在我以前用Java时就非常头疼,不过解决办法还是很简单的:
 
1、windows下:修改my.ini文件,有两处default-character-set=latin1都改为default-character-set=utf8重启既可。
2、linux下:vim /etc/my.cnf(若没有可查看/etc/mysql/my.cnf)在[mysqld]下加入 default-character-set = utf8,[client]下加入default-character-set = utf8
 :wq保存退出
 
然尔这次用python也出现令人头疼的乱码码问题:数据库中是UTF-8编码,用上面的代码插入数据后在数据库中查看时,中文会乱码,但再用python查询时中文却会正确显示。
 
 
查询:
 
 
Python代码 
# -*- coding: utf-8 -*- 
'''''
Created on 2011-9-23
 
@author: HuangHua
''' 
import MySQLdb 
 
conn = MySQLdb.Connect(host='localhost', user='root', passwd='root', db='python') 
 
cursor = conn.cursor() 
 
count = cursor.execute('select * from test') 
 
print '总共有%s条记录',count 
 
#获取一条记录,每条记录做为一个无组返回  
result = cursor.fetchone(); 
print result 
print 'ID: %s info: %s' % result 
 
#获取多条记录,注意由于之前执行了fetchone(),所以游标已经指到第二条记录了 ,也就是从第二条开始的所有记录 
results = cursor.fetchmany(2) 
for r in results: 
    print r 
 
print '获取 所有结果 :' 
#重置游标位置,0为偏移量,mode=absolute | relative,默认为relative 
cursor.scroll(0, mode='absolute') 
#获取所有结果 
results = cursor.fetchall() 
for r in results: 
    print r[1] 
 
cursor.close() 
 
查询后中文会正确显示,但在数据库中却是乱码的。经过我从网上查找,发现用一个属性有可搞定:

Python代码 
conn = MySQLdb.Connect(host='localhost', user='root', passwd='root', db='python') 
 
中加一个属性:
 
Python代码 
conn = MySQLdb.Connect(host='localhost', user='root', passwd='root', db='python',charset='utf8') 
charset是要跟你数据库的编码一样,如果是数据库是gb2312 ,则写charset='gb2312'。

作者“qq404708194-sina-com”
 

相关内容

    暂无相关文章

评论关闭