使用MySQL insert命令运行python时参数出错

2024-09-22 16:30:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从Python插入MySQL

mysql.connector.errors.ProgrammingError: Not enough parameters for the SQL statement;

我在网上看了一下,我知道这和tuble有关,但我不知道要修改什么,我四处看了看我的代码,在responce_data中有10个项目,在SQL中有10个项目,我有10%s,所以我不知道哪里出错了

 import urllib.parse
import requests
import mysql.connector


mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="**",
  database="flightdata"
)

mycursor = mydb.cursor()


main_api = 'https://www.sydneyairport.com.au/_a/flights/?query=&flightType=departure&terminalType=domestic&date=2019-11-10&sortColumn=scheduled_time&ascending=true&showAll=true'

address = 'lhr'
url = main_api + urllib.parse.urlencode({address: address})

response_data = requests.get(url).json()
for element in response_data['flightData']:
    flight_id = element['id']
    airline = element['airline']
    destination = element['destinations']
    flightNumbers = element['flightNumbers']
    scheduledTime = element['scheduledTime']
    estimatedTime = element['estimatedTime']
    scheduledDate = element['scheduledDate']
    latestTime = element['latestTime']
    status = element['status']
    statusColor = element['statusColor']

    sql = "INSERT INTO flightinfo (id, airline, destinations, flightNumbers, scheduledTime, estimatedTime, scheduledDate, latestTime, status, statusColor) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"

    #sql = "INSERT INTO flightinfo (flight_id, airline, destination, flightNumbers, scheduledTime, estimatedTime, estimatedTime, scheduledDate, latestTime, status, statusColor ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s ,%s))"
    val = [(flight_id, airline, " ".join(destination), ", ".join(flightNumbers), scheduledTime, estimatedTime,
            scheduledDate, latestTime, status, statusColor)]

mycursor.executemany(sql, val)

mydb.commit()

print(mycursor.rowcount, "was inserted.")


print(airline, destination, flightNumbers, scheduledTime, "Estimated Time:" + " " + estimatedTime, "Scheduled Date:" + " " + scheduledDate, "Latest Time:" + " " + latestTime, "Status:" + " " +status, "Status Color:" + " " + statusColor)

Tags: importiddataconnectorstatusmysqlelementdestination
1条回答
网友
1楼 · 发布于 2024-09-22 16:30:31

删除val中的尾部,,并将val更改为

val = [(flight_id, airline, destination, flightNumbers, scheduledTime, estimatedTime, scheduledDate, latestTime, status, statusColor)]

别忘了将sql修复为

sql = "INSERT INTO flightinfo (flight_id, airline, destination, flightNumbers, scheduledTime, estimatedTime, scheduledDate, latestTime, status, statusColor) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"

更新: 为了避免

TypeError: Python 'list' cannot be converted to a MySQL type

例如,您可以将相关字段转换为字符串。你知道吗

val = [(flight_id, airline, " ".join(destination), ", ".join(flightNumbers), scheduledTime, estimatedTime, scheduledDate, latestTime, status, statusColor)]

相关问题 更多 >