Python连接MySQL数据库通信实例以及中文乱码的解决办法
(2011-11-14 08:40:16)我的开发环境:Windows 7 + Navicat for MySQL + Python 2.7
想要Python和MySQL进行通信,就需要根据自己开发时的操作系统下载相对应的Python和MySQL的接口模块,并编译安装。我下载的是MySQL-python-1.2.3.win32-py2.7.exe,下载后双击安装即可。准备工作都做好后,就可以使用python进行数据库访问了,下面给出一个简单的实例:
#!/usr/bin/env python import sys import MySQLdb #Connect to database try: except MySQLdb.Error, e: #Get a cursor to execute sql command cursor = conn.cursor() cursor.execute("DROP TABLE IF EXISTS student") cursor.execute(""" cursor.execute(""" sqlcmd = "SELECT * from student" cursor.execute(sqlcmd) #Deal with the results results = cursor.fetchall() for row in results: print "Number of rows returned: %d" % cursor.rowcount #Close cursor and connection cursor.close() conn.close() |
如果数据库中存储的数据包含中文,那么在python的控制台打印查询结果时可能会出现乱码,下面是解决方案:
1.
#encoding=utf-8
2.
conn = MySQLdb.connect(host = "localhost",
3.
Import sys
reload(sys)
sys.setdefaultencoding("utf-8")
4.
[client]
default-character-set = utf8
[mysqld]
default-character-set = utf8
经过我的测试,一般来说完成前两步就可以正常输出中文了,以下是修改后的脚本:
#!/usr/bin/env python #encoding=utf-8 import sys import MySQLdb #reload(sys) #sys.setdefaultencoding("utf-8") #Connect to database try: except MySQLdb.Error, e: #Get a cursor to execute sql command cursor = conn.cursor() cursor.execute("DROP TABLE IF EXISTS student") cursor.execute(""" cursor.execute(""" sqlcmd = "SELECT * from student" cursor.execute(sqlcmd) #Deal with the results results = cursor.fetchall() for row in results: print "Number of rows returned: %d" % cursor.rowcount #Close cursor and connection cursor.close() conn.close() |