None null mysql,在准备的INSERT语句中无法在python mysql.connector中使用None(NULL)值

When trying to use prepared cursor and insert NULL values the mysql.connector reports an error:

mysql.Error: 1210 (HY000): Incorrect arguments to mysqld_stmt_execute

Here is a code that shows this exactly.

from __future__ import print_function

import mysql.connector

def execsql(cursor, sqlstmt):

try:

cursor.execute(sqlstmt)

except mysql.connector.Error as e:

print("mysql.Error: %s" % e)

print(cursor._executed, '\n')

def execsqlwithparams(cursor, sqlstmt, params):

try:

cursor.execute(sqlstmt, params)

except mysql.connector.Error as e:

print("mysql.Error: %s" % e)

print(cursor._executed, "params:", params, '\n')

def main():

print("mysql.connector.__version__", mysql.connector.__version__)

db = mysql.connector.connect(db="test")

print("mysql.db. get server version", db.get_server_version())

c1 = db.cursor()

c2 = db.cursor(prepared=False)

c3 = db.cursor(prepared=True)

execsql(c1, "drop table if exists test1")

execsql(c1, "create table test1 (col1 int not null, col2 int null, primary key(col1))")

print("insert with pure SQL")

execsql(c1, "insert into test1(col1,col2) values (1, 1)")

execsql(c1, "insert into test1(col1,col2) values (2, NULL)")

print("insert with prepared statement format %s")

sql = "insert into test1(col1,col2) values (%s, %s)"

execsql(c2, sql)

execsqlwithparams(c2, sql, (20, 20))

execsqlwithparams(c2, sql, (21, None))

print("insert with prepared statement format %s using prepared cursor")

sql = "insert into test1(col1,col2) values (%s, %s)"

execsql(c3, sql)

execsqlwithparams(c3, sql, (30, 30))

execsqlwithparams(c3, sql, (31, None))

execsql(c1, "select * from test1")

row = c1.fetchone()

while row:

print(row)

row = c1.fetchone()

db.close()

if __name__ == '__main__':

status = main()

The output is like this:

mysql.connector.__version__ 1.2.2

mysql.db. get server version (5, 5, 37)

drop table if exists test1

create table test1 (col1 int not null, col2 int null, primary key(col1))

insert with pure SQL

insert into test1(col1,col2) values (1, 1)

insert into test1(col1,col2) values (2, NULL)

insert with prepared statement format %s

mysql.Error: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s, %s)' at line 1

insert into test1(col1,col2) values (%s, %s)

insert into test1(col1,col2) values (20, 20) params: (20, 20)

insert into test1(col1,col2) values (21, NULL) params: (21, None)

insert with prepared statement format %s using prepared cursor

insert into test1(col1,col2) values (%s, %s)

insert into test1(col1,col2) values (%s, %s) params: (30, 30)

mysql.Error: 1210 (HY000): Incorrect arguments to mysqld_stmt_execute

insert into test1(col1,col2) values (%s, %s) params: (31, None)

select * from test1

(1, 1)

(2, None)

(20, 20)

(21, None)

(30, 30)

The unexpected result is this:

mysql.Error: 1210 (HY000): Incorrect arguments to mysqld_stmt_execute

insert into test1(col1,col2) values (%s, %s) params: (31, None)

And missing row (31, None) from the database.

解决方案

Your problem related with the None passed in the last case can be caused by the fact that the None is not being interpreted as the type defined in your table.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用pymysql进行批量插入数据,你可以按照以下步骤进行操作: 1. 首先,确保你已经连接到了MySQL数据库。你可以使用pymysql.connect函数来连接数据库,指定正确的主机名、用户名、密码、端口号等参数。 2. 接着,创建一个游标对象,可以使用cursor()方法来实现[2]。 3. 然后,准备你要插入的数据。你可以将要插入的数据保存在一个列表或元组。 4. 使用executemany()方法来批量执行插入操作。该方法需要两个参数,第一个参数是插入的SQL语句,第二个参数是要插入的数据。你可以使用占位符(?)来代替实际的。例如,"INSERT INTO table_name (column1, column2, ...) VALUES (?, ?, ...)"。 下面是一个示例代码,展示了如何使用pymysql进行批量插入数据: ```python import pymysql # 连接到数据库 db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='work1') cursor = db.cursor() # 准备插入的数据 data = [ ('1', '张三', 20, 90, 'A'), ('2', '李四', 21, 85, 'B'), ('3', '王五', 22, 95, 'A') ] # 执行插入操作 sql = 'INSERT INTO grade(id, name, age, score, class) VALUES (%s, %s, %s, %s, %s)' cursor.executemany(sql, data) # 提交更改 db.commit() # 关闭游标和数据库连接 cursor.close() db.close() ``` 在上面的示例代码,我们首先连接到数据库,然后准备插入的数据,接着使用executemany()方法批量执行插入操作,最后提交更改并关闭游标和数据库连接。 希望这个示例能够帮助你了解如何使用pymysql进行批量插入数据。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Python操控mysql批量插入数据的实现方法](https://download.csdn.net/download/weixin_38713039/13705682)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [MySQL(一) Python操控mysql批量插入数据](https://blog.csdn.net/shine4869/article/details/103988174)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值