gpt4 book ai didi

Python 3 pymysql 插入空日期时间字段

转载 作者:行者123 更新时间:2023-11-29 19:42:05 26 4
gpt4 key购买 nike

我有一个表,其中namevarchar(50)ctimedatetime。如果我在 MySQL 中执行 insert into atable (name, ctime) values ('aname', NULL) 它就会起作用。

在 Python 3 中,我尝试了以下方法(全部生成错误):

conn = pymysql.connect(host='ahost', port=3306, user='auser', passwd='apasswd', db='adb')

cur = conn.cursor()

[尝试1]

cur.execute("insert into atable (name, ctime) values (%s, '%s'), ('aname', '')

pymysql.err.InternalError: (1292, "Incorrect datetime value: '' for column 'ctime' at row 1")

[尝试2]

cur.execute("insert into atable (name, ctime) values (%s, %s), ('aname', '')

pymysql.err.ProgrammingError: (1064, "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 ')' at line 1")

[尝试3]

cur.execute("insert into atable (name, ctime) values (%s, '%s'), ('aname', None)

pymysql.err.InternalError: (1292, "Incorrect datetime value: 'None' for column 'ctime' at row 1")

[尝试4]

cur.execute("insert into atable (name, ctime) values (%s, %s), ('aname', None)

pymysql.err.InternalError: (1054, "Unknown column 'None' in 'field list'")

如有任何帮助,我们将不胜感激。

最佳答案

在这种情况下,您不需要传递ctime,只需传递您实际设置的值即可。

sql = "INSERT INTO `atable` (`name`) VALUES (%s)"
rows = cursor.execute(sql, ('aname2'))
print("insert:", rows)

我运行代码并按预期工作,完整代码:

import pymysql

def main():
try:
conn = pymysql.connect(
host='localhost', user='@@', password='##',
db='dn_name'
)
with conn.cursor() as cursor:
sql = "INSERT INTO `atable` (`name`) VALUES (%s)"
rows = cursor.execute(sql, ('aname2'))
print("insert:", rows)

except Exception as e:
conn.rollback()
raise e
else:
conn.commit()
finally:
conn.close()

if __name__ == '__main__':
main()

关于Python 3 pymysql 插入空日期时间字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41292700/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com