笔者在使用python的pymysql模块的connect方法报错了
报错信息:pymysql.err.OperationalError: (1054, “Unknown column ‘关羽’ in ‘field list’”)
# 重要代码部分
# 使用cursor的excute向mysql插入一条数据(原代码)
sql = f"""insert into customers values (0, {customer_name}, {customer_address}, {customer_tel}, {customer_password});"""
print(f"--->{sql}<---") # 测试代码
count = cursor.execute(sql)
# 测试代码
# count = cursor.execute('insert into customers values (0, "刘备", "广州", 110, 123)')
print(f"有---->{count}<-----行发生了改变")
# 提交该操作
conn.commit()
表结构
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| id | int unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| address | varchar(20) | NO | | NULL | |
| tel | int unsigned | NO | | NULL | |
| password | int unsigned | NO | | NULL | |
+----------+--------------+------+-----+---------+----------------+
笔记校对了一下mysql语句发现没有问题,使用以下代码测试校对一下
将sql字符串单独打印出来,与正确的语句对比,也是没有区别
count = cursor.execute('insert into customers values (0, "刘备", "广州", 110, 123)') # 可以成功插入数据
sql = f"""insert into customers values (0, '{customer_name}', '{customer_address}', '{customer_tel}', '{customer_password}');"""
print(f"--->{sql}<---") # 测试代码
最后查询了一下,pymysql在进行插入数据时,字符串类型的数据,需加单引号’ '才能插入成功
哎,建议大家以后字符串类型都是使用单引号吧
往字符串类型的数据添加单引号,修改了代码
sql = f"""insert into customers values (0, '{customer_name}', '{customer_address}', {customer_tel}, {customer_password});"""