gpt4 book ai didi

python - 使用 python 更新 mysql 中的列时出错

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

基本上,我的代码所做的只是更新我创建的数据库,其中所有列均为“varchar”格式。我的代码能够在时间范围为“10:00-10:15”时创建一个新条目。但是,当时间范围变为“10:15-10:30”或基本上任何其他时间范围时无法更新它。我的代码如下:

import time
import MySQLdb
from MySQLdb import *
import datetime
import json

date = time.localtime()
year_mon_date_day = [date.tm_year, date.tm_mon, date.tm_mday, date.tm_wday]

column = ''
if date.tm_hour==10:
if date.tm_min<=15:
column = "10:00-10:15"
elif date.tm_min<=30:
column = "10:15-10:30"
elif date.tm_min <= 45:
column = "10:30-10:45"
elif date.tm_min <= 60:
column = "10:45-11:00"

elif date.tm_hour==11:
if date.tm_min<=15:
column = "11:00-11:15"
elif date.tm_min<=30:
column = "11:15-11:30"
elif date.tm_min <= 45:
column = "11:30-11:45"
elif date.tm_min <= 60:
column = "11:45-12:00"

elif date.tm_hour==12:
if date.tm_min<=15:
column = "12:00-12:15"
elif date.tm_min<=30:
column = "12:15-12:30"
elif date.tm_min <= 45:
column = "12:30-12:45"
elif date.tm_min <= 60:
column = "12:45-01:00"

elif date.tm_hour==13:
if date.tm_min<=15:
column = "01:00-01:15"
elif date.tm_min<=30:
column = "01:15-01:30"
elif date.tm_min <= 45:
column = "01:30-01:45"
elif date.tm_min <= 60:
column = "01:45-02:00"

else:
pass

db = MySQLdb.connect(host='localhost', user='root', passwd='4747',db='traffic_record')
cursor=db.cursor()


if column == "10:00-10:15":
query = '''INSERT INTO `traffic_record`.`RoadA` ( `Date`,`Day`,`''' + column + '''`) VALUES ('%s','%s','%s')'''
value = (year_mon_date_day,date.tm_wday, 9)
else:
query = '''UPDATE `traffic_record`.`RoadA` SET `''' + column + '''`=`%s` WHERE `Date`=''' + str(year_mon_date_day) + '''`'''
value = (3)

cursor.execute(query, value)

db.commit()
db.close()

当我尝试在“10:00-10:15”以外的任何其他时间范围内运行代码时,我的代码会出现以下错误。我收到以下错误:

/usr/bin/python2.7 /home/sparsha/PycharmProjects/MachineLearning/fill_table.py
Traceback (most recent call last):
File "/home/sparsha/PycharmProjects/MachineLearning/fill_table.py", line 83, in <module>
cursor.execute(query, value)
File "/usr/local/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 187, in execute
query = query % tuple([db.literal(item) for item in args])
TypeError: 'int' object is not iterable
Process finished with exit code 1

我无法解决这个问题。任何帮助将不胜感激。谢谢。

最佳答案

您应该将值设置为可迭代:

value = (3,)
# ^

你得到的(3)是一个带有分组括号的整数。括号不会使整数成为可迭代的。但是添加该逗号使其成为一个单例元组,这就是您想要的。

关于python - 使用 python 更新 mysql 中的列时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38563131/

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