我的表格name
为varchar(50)
,ctime
为datetime
。
如果我在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'")
任何帮助都将不胜感激。
答案 0 :(得分:0)
在这种情况下,您不需要传递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()