python连接数据库报错问题

python连接数据库报错问题

python写添加语句的时候报错:

# 添加语句
sql = "insert into t_user(t_id,t_name,t_age)values (%(t_id)s,%(t_name)s,%(t_age)s)" # % 和 s 是占位符
# 执行sql语句t_user
cursor.execute(sql,{
    
    "t_id":"3","t_name":"啊aaa","t_age":"10"})

报错问题

Traceback (most recent call last):
  File "E:\python_exercise\pythonDemo\test\Test.py", line 29, in <module>
    cursor.execute(sql,{
    
    "t_id啊":"3","t_name":"aaa","t_age":"10"})
  File "E:\python\lib\site-packages\pymysql\cursors.py", line 146, in execute
    query = self.mogrify(query, args)
  File "E:\python\lib\site-packages\pymysql\cursors.py", line 125, in mogrify
    query = query % self._escape_args(args, conn)
KeyError: 't_id'

解决方法:可能是你在建表的时候没有设置中文的字符集

CHARACTER SET utf8 COLLATE utf8_general_ci

如果没有给表设置字符集的话,建表的时候会根据数据库的字符集建表

create table t_user(
	t_id int(3),
	t_name varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci,
	t_age int(3)
);

猜你喜欢

转载自blog.csdn.net/weixin_45716754/article/details/117742796