我的目标是更新mysql数据库中的现有表,将update语句的所有变量作为用户的输入。我正在使用mysqlconnector与python接口
coltbu=input("Now enter the name of the column whose value for that row/condition is to be updated")
if coltbu=="dob":
y1=input("Enter the value to be set for date of joining in yyyy-mm-dd")
elif col=="id":
nval=int(input("Enter the value to be set for salary"))
else:
nval=input("Enter the value to be set for this column")
x='%d-%m-%Y'
tup=(coltbu,y1,x,col,val)
print(tup)
cursor1.execute("Update student set %s=str_to_date(%s,%s) where %s=%s"%tup)
con1.commit()
con1.close()
在互联网上苦苦寻找解决方案后,我有很多变化,但我似乎找不到任何有效的方法。总会出现一些错误 在这种情况下,我使用的表是 image of table
我试图执行的命令是
update student set dob='2003-09-12' where id=6;
我还尝试使用datetime来实现这一点
coltbu=input("Now enter the name of the column whose value for that row/condition is to be updated")
if coltbu=="dob":
y=int(input("Enter the value to be set for dob in yyyy/mm/dd. First enter year and hit enter"))
m=int(input("Now enter month"))
d=int(input("Now enter date"))
nval=datetime.date(datetime(y,m,d))
elif col=="id":
nval=int(input("Enter the value to be set for id"))
else:
nval=input("Enter the value to be set for this column")
tup=(int(coltbu,nval,col,val)
print(tup)
cursor1.execute("Update student set %s=%s where %s=%s"%tup)
con1.commit()
con1.close()
但这带来了一个非常奇怪的错误。它会说
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/mysql/connector/connection_cext.py", line 489, in cmd_query
raw_as_string=raw_as_string)
_mysql_connector.MySQLInterfaceError: Incorrect date value: '1993' for column 'dob' at row 4
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/aliziamojiz/Documents/Alizia/12/prac1.py", line 118, in <module>
f4()
File "/Users/aliziamojiz/Documents/Alizia/12/prac1.py", line 113, in f4
cursor1.execute("Update student set %s=%s where %s=%s"%tup)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/mysql/connector/cursor_cext.py", line 266, in execute
raw_as_string=self._raw_as_string)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/mysql/connector/connection_cext.py", line 492, in cmd_query
sqlstate=exc.sqlstate)
mysql.connector.errors.DataError: 1292 (22007): Incorrect date value: '1993' for column 'dob' at row 4
然而,无论是在我的代码中还是在我提供的输入中,我都没有进入1993年
我现在卡住了。如何将日期作为python程序的输入,并在mysql表的更新命令中使用它。 请帮忙。 提前感谢:)
您使用datetime获取日期的方式似乎有些奇怪^如果日期的格式不符合预期或日期无效,{}将抛出
ValueError
。通常是这样使用的:然后,您可以使用输入日期用
dateObject.date()
更新表。此外,我还建议您在使用
execute
时分离SQL查询中的值(以防止SQL注入),如下所示:相关问题 更多 >
编程相关推荐