pymysql insert ProgrammingError1064

本文探讨了使用pymysql向数据库插入长文本时遇到的错误:SQL语法错误。通过调整SQL语句中占位符的使用方式,成功解决了问题。正确的做法是避免在%s占位符周围添加额外的引号。

用pymysql向数据库插入比较长的文本,一直出错:
Error:ProgrammingError: (1064, "You have an error in your SQL syntax;…

sql = "INSERT INTO train_dataset(news,label) VALUES ("+"\""+new+"\""+")"
sql =  "INSERT INTO train_dataset(news,label) VALUES ('%s)"%new
 sql = "INSERT INTO train_dataset(news,label) VALUES ('%s)"
 cursor.execute(sql,(line))

都报这个错误
后来发现,是sql里这个’%s’不能加引号……

cursor = db.cursor()  # 获取游标

sql = "INSERT INTO test_dataset(news) VALUES (%s)"
cursor.execute(sql,(line))
db.commit()

这个占位符一直不用’'的啊!

`pymysql` 出现 `ProgrammingError (1110, "Column 'mobile2' specified twice")` 错误,表明在 SQL 语句里 `mobile2` 列被重复指定了,这属于编程错误,一般是 SQL 语句的语法有误。 解决该问题的步骤如下: 1. **检查 SQL 语句**:要保证 SQL 语句里没有重复指定 `mobile2` 列。例如,在 `INSERT` 或者 `CREATE TABLE` 语句中,一个列名只能出现一次。 2. **检查动态生成的 SQL 语句**:若 SQL 语句是动态生成的,要确保生成逻辑不会重复添加列名。 以下是检查 `INSERT` 语句的示例代码: ```python import pymysql try: # 使用参数创建链接 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='Lmx18287620110', db='python', charset='utf8', connect_timeout=1000) # 使用 connent 链接数据库 cursor = conn.cursor() # 示例:检查 INSERT 语句 insert_sql = "INSERT INTO your_table (column1, mobile2, column3) VALUES (%s, %s, %s)" # 确保列名没有重复 values = ('value1', 'value2', 'value3') cursor.execute(insert_sql, values) conn.commit() except pymysql.ProgrammingError as error: errno = error.args[0] if errno == 1110: print("错误:Column 'mobile2' specified twice,请检查 SQL 语句。") else: print(f"其他编程错误: {error}") finally: if conn: conn.close() ``` 3. **使用错误处理机制**:可以使用引用[1]里的错误处理机制来捕获并处理该错误。 ```python import pymysql # 错误代码映射表示例 error_mapping = { # 编程错误(语法、表不存在等) 1050: pymysql.ProgrammingError, # Table already exists 1064: pymysql.ProgrammingError, # Syntax error 1110: pymysql.ProgrammingError, # Column specified twice # 其他错误类型... } # 自定义错误处理 def handle_mysql_error(error): errno = error.args[0] if error.args else None if errno in error_mapping: error_class = error_mapping[errno] raise error_class(*error.args) from error else: raise error try: # 使用参数创建链接 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='Lmx18287620110', db='python', charset='utf8', connect_timeout=1000) # 使用 connent 链接数据库 cursor = conn.cursor() # 示例 SQL 语句 sql = "INSERT INTO your_table (column1, mobile2, mobile2, column3) VALUES ('value1', 'value2', 'value3', 'value4')" cursor.execute(sql) conn.commit() except pymysql.Error as error: handle_mysql_error(error) finally: if conn: conn.close() ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值