Python中使用MySQLdb连接MySQL数据库出错(改用PyMySQL连接数据库)

       在Python中使用MySQLdb模块连接MySQL数据库时,由于Python 3.x中已经不支持这个模块了,取而代之的是PyMySQL。因此,首先需要安装PyMySQL,只需将链接文章中的改为pip install pymysql,安装完成之后就可以导入该模块,示例程序如下:

import os, sys
import pymysql
# 连接数据库
try:
    conn = pymysql.connect(host='localhost',user='root',passwd='',db='abook')       
except Exception as e:
    print (e)                               # 打印错误
    sys.exit()
cursor = conn.cursor()
sql = "insert into address(name, address) values (%s, %s)" 
values = (("张张", "北京海淀区"), ("李李", "北京海淀区"), ("王王", "北京海淀区"))
try:
    cursor.executemany(sql, values)         # 插入多条数据
except Exception as e:
    print (e)                               # 打印错误
sql = "select * from address"
cursor.execute(sql)                         # 查询数据
data = cursor.fetchall()
if data:
    for x in data:
        print (x[0], x[1])
cursor.close()                              # 关闭游标
conn.close()

但是在运行程序的时候会出现如下问题:

'latin-1' codec can't encode characters in position 2-3:ordinal not in range(256)


只需要将conn = pymysql.connect(host='localhost',user='root',passwd='',db='abook')改为conn = pymysql.connect(host='localhost',user='root',passwd='',db='abook',charset='utf8')即可。

猜你喜欢

转载自blog.csdn.net/jisuanjiguoba/article/details/73188096