在使用Python3的模块PyMysql连接数据库时,怎么都无法插入,报了这个异常
各种倒腾后发现是在连接的时候没有指定以什么编码连接导致的错误
之前的代码:
#!/usr/bin/python3
import pymysql
def insert_law(title, content):
# 打开数据库连接
db = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='law')
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 插入语句
sql = 'INSERT INTO tb_law(title, content) \
VALUES (\'%s\', \'%s\' )' % \
(title, content)
try:
# 执行sql语句
cursor.execute(sql)
# 执行sql语句
db.commit()
except Exception as e:
print(e)
db.rollback()
# 关闭数据库连接
db.close()在pymysql.connect 之后指定 charset='utf8'
#!/usr/bin/python3
import pymysql
def insert_law(title, content):
# 打开数据库连接
db = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='law', charset='utf8')
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 插入语句
sql = 'INSERT INTO tb_law(title, content) \
VALUES (\'%s\', \'%s\' )' % \
(title, content)
try:
# 执行sql语句
cursor.execute(sql)
# 执行sql语句
db.commit()
except Exception as e:
print(e)
db.rollback()
# 关闭数据库连接
db.close()错误解决

本文介绍了一个关于使用Python3的PyMysql模块连接数据库时遇到的问题,即无法插入数据并出现异常的情况。通过指定正确的字符集(charset='utf8'),成功解决了这一问题。
4万+





