【问题标题】:inserting null dates in MySql with pymysql使用 pymysql 在 MySql 中插入空日期
【发布时间】:2019-02-19 01:52:45
【问题描述】:

我正在尝试使用 pymysql 和参数将日期插入 MySql 数据库。有些行有一个日期字段,但对于其他一些行,缺少特定的日期字段。空行给出“pymysql.err.InternalError: (1292, “Incorrect date value:”类型的错误。下面是一段重现错误的代码:

import pymysql
db=pymysql.connect("localhost","testuser","test1234","TESTDB")
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()
print ("Database version : %s " % data)

query = "DROP TABLE IF EXISTS birthdays"
cursor.execute(query)

query="CREATE TABLE birthdays(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,\
name VARCHAR(20),\
birthday DATE NULL DEFAULT NULL)"
cursor.execute(query)
db.commit()

birthdays={'David':'2014-05-22','Larry':'014-05-22', 'Barry':''}

for k,v in birthdays.items():
    print(k,v)
    query="INSERT INTO birthdays (name,birthday) VALUES ('%s','%s')"%(k,v)
    cursor.execute(query)
    db.commit()

db.close()

问题在于巴里及其空日期。我尝试将 Barry 的日期设置为 None,但它不起作用。如果我将其设置为“NULL”并从日期参数中删除引号(('%s',%s)而不是('%s','%s'))它适用于巴里,但请注意其他人.

非常感谢您,

加布里埃尔·维达尔

【问题讨论】:

    标签: python mysql date null


    【解决方案1】:

    您可以使用下面的代码,我刚刚在您的数组中更改并设置 'Barry':None 因为当使用 mysqldb 和 cursor.execute() 时,传递值 None:

    birthdays={'David':'2014-05-22','Larry':'014-05-22', 'Barry':None}
    
    for k,v in birthdays.items():
        print(k,v)
        query="INSERT INTO birthdays (name,birthday) VALUES ('%s','%s')"%(k,v)
        cursor.execute(query)
        db.commit()
    
    db.close()
    

    更多详情here

    【讨论】:

    • 嗨,谢谢,但它对我不起作用。起作用的是将值作为元组作为参数传递给 cursor.execute(query,args)
    • 你好@user1862963 你能试试:cursor.execute("INSERT INTO birthdays (name,birthday) VALUES ('%s','%s')", (k,v))
    • 嗨,是的,这就是我在第一条评论中的意思,但是您必须从类型或值中删除引号,如下所示: cursor.execute("INSERT INTObirthdays (name,birthday)值 (%s,%s)", (k,v))。谢谢
    【解决方案2】:

    万一有人路过:

    以下代码 sn -p 解决了您遇到的问题。请注意,您应该将您的执行语句保留在 for 循环之外,以尽量减少您与数据库进行的连接数。

    birthdays = {'David':'2014-05-22','Larry':'2014-05-22', 'Barry':'NULL'}
    values = ""
    for k,v in birthdays.items():
        values += "('%s', '%s')," % (k,v)
    
    values = values[:-1].replace("'NULL'", "NULL")  # Drop the final comma and the quotes of NULL values
    query = f"INSERT INTO birthdays (name,birthday) VALUES {values}"  # >= 3.6
    cursor.execute(query)  # Interaction with the database occurs only once
    db.commit()
    

    这会生成以下语句:

    INSERT INTO birthdays (name,birthday) VALUES ('David', '2014-05-22'),('Larry', '2014-05-22'),('Barry', NULL)
    

    这是一个有效的sql语句

    【讨论】:

      猜你喜欢
      • 2013-07-20
      • 2011-12-08
      • 2019-07-13
      • 1970-01-01
      • 2017-04-13
      • 1970-01-01
      • 2013-09-15
      • 1970-01-01
      相关资源
      最近更新 更多