无法使用 python、变量和 auto_increment 插入到 mySQL 数据库中

Unable to insert into mySQL database using python, variables and auto_increment

我希望我的格式没问题,因为这是我第一次使用 Whosebug

无论我如何更改我的代码和方法,我在执行这段代码时都会遇到同样的错误

File "/usr/lib/python3/dist-packages/mysql/connector/cursor.py", line 83, in call return bytes(self.params[index]) IndexError: tuple index out of range

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "sqlTest.py", line 40, in mycursor.execute(sql,val) File "/usr/lib/python3/dist-packages/mysql/connector/cursor.py", line 558, in execute stmt = RE_PY_PARAM.sub(psub, stmt) File "/usr/lib/python3/dist-packages/mysql/connector/cursor.py", line 86, in call "Not enough parameters for the SQL statement") mysql.connector.errors.ProgrammingError: Not enough parameters for the SQL statement

这是我的主要项目的一部分,它将记录某些变量的当前值以及 GPS 坐标和时间戳。

据我所见,主要问题与数据库有关,而我本应只需要 7 个条目。

我主要遵循 https://www.w3schools.com/python/python_mysql_insert.asp 教程,因为我不太熟悉一起使用 python 和 mySQL。

#Initialize mySQL databse connection
mydb = mysql.connector.connect(
  host="themySQLserver.net",
  user="myUSername",
  passwd="_____",
  database="24totheTLE"
)

这些变量通常由主程序设置,但我手动设置它们以进行故障排除

top_since_epoch = 4
left_since_epoch = 1
bottom_since_epoch = 5
right_since_epoch = 3

这是调用 python2 脚本获取 gps 数据的代码

fullgps = os.popen("python gps.py").read()
gps_split = fullgps.split(";")
gps_split[1] = gps_split[1].rstrip()
s1 = float(gps_split[0])
s2 = float(gps_split[1])

我的数据库的主键 "LogNum" 设置为自动递增,因此我没有在我的代码中提到它。

ts = time.time()
timestam = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
mycursor = mydb.cursor()
sql = "INSERT INTO records (TimeStamp,CarsTop,CarsLeft,CarsRight,CarsBottom,GPSLong,GPSLat) VALUES (%s, %s, %s, %s, %s, %s, %s)"
val = [timestam,top_since_epoch,left_since_epoch,bottom_since_epoch,s2,s1]
mycursor.execute(sql,val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")

感谢所有回复的人。

终于找到答案了

问题是我用来传递日期时间信息的代码没有设置为与“mysql.connector”交互,这是通过更新代码以使用 MySQLdb 库来解决的:

这段代码对我有用

#Initialize mySQL databse connection
mydb = MySQLdb.connect(
  host="sql24.cpt1.host-h.net",
  user="stonesp_1",
  passwd="______",
  database="24totheTLE"
)
print("5 minutes")
fullgps = os.popen("python gps.py").read()
gps_split = fullgps.split(";")

s1 = float(gps_split[0])
s2 = float(gps_split[1])
print(s1)
print(s2)
ts = time.time()
timecur = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
print(timecur)
mycursor = mydb.cursor()

sql = "INSERT INTO records (TimeStamp,CarsTop,CarsLeft,CarsRight,CarsBottom,GPSLong,GPSLat) VALUES (%s,%s,%s,%s,%s,%s,%s)"
val = [timecur,top_since_epoch,left_since_epoch,right_since_epoch,bottom_since_epoch,s2,s1]

mycursor.execute(sql,val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
mydb.close()