【问题标题】:MySQL Python query syntax mistake on INSERT when it seems to be satisfying?似乎令人满意时,INSERT 上的 MySQL Python 查询语法错误?
【发布时间】:2019-02-21 21:00:19
【问题描述】:

我正在为出租车服务开发示例数据库,并尝试使用 Python 和 mysql.connector 库用一些数据填充 PhoneCall 表。 PhoneCall 表的列是:

  • idCall, int(11), PRIMARY KEY
  • Operator_idOperator, int(11), NOT NULL, FOREIGN KEY
  • Client_idClient, int(11), NOT NULL, FOREIGN KEY
  • datetimeValue, datetime
  • Duration, int(11)

我声明一个空列表并生成一些数据来填充表格:

  • query = "INSERT INTO TaxiTest.PhoneCall (idCall, Operator_idOperator, Client_idClient, datetimeValue, Duration) VALUES (%s, %s, %s, %s, %s)"

之后,我生成数据

data = []
for i in range(1500):
    idCall = i + 1
    (Operator_idOperator, Client_idClient) = (20, 21) # Sample ints
    datetime_value = datetime.now()
    duration = 60
    t_tuple = (idCall, Operator_idOperator, Client_idClient, datetime_value, duration)
    data.append(t_tuple)

接下来,我尝试使用 cursor.executemany(query, data) 语法插入数据:

cnx = mysql.connector.connect(**config)
cnx.autocommit = True
cursor = cnx.cursor()
try:
    cursor.executemany(query, data)
    log = cursor.fetchall()
    print("Result: " + log)
except mysql.connector.Error as err:
    print(err.msg)

所以,结果是:

  • Data[0]: (1, 46, 2521, datetime.datetime(2018, 9, 17, 22, 44, 20, 159722), 55)
  • 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 'TaxiTest.PhoneCall' at line 1

虽然我已经在这个数据库中填写了大约 5 个表,但我没有发现这个 INSERT 语句中有任何错误。

似乎唯一的解决方案是将所有1500条数据写入output.txt文件并使用MySQL Workbench执行,因为使用MySQL Workbench插入时没有错误,但这是不受欢迎。

附:这是我在 StackOverflow 上的第一个问题。等了这么久才得到一些“硬币”来评论和评价其他问题和答案。

【问题讨论】:

    标签: python mysql-python mysql-connector-python


    【解决方案1】:

    如果不尝试,我会说它是 datetime 对象。

    你可以试试这个代码:

    from datetime import datetime
    datetime_value = datetime.now()
    formatted_date = datetime_value.strftime('%Y-%m-%d %H:%M:%S')
    

    【讨论】:

    • 使用 MySQL Workbench 从带有“INSERT ...”语句的 SQL 脚本文件插入。虽然,无法使用 mysql.connector 模块将数据插入数据库。
    • 在外部函数中发现错误,答案完全正确
    • 我使用 MySQLdb 导入,所以我希望它是一样的。我很高兴这个解决方案对你有用。
    猜你喜欢
    • 2015-07-17
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多