【问题标题】:How to write proper MySQL Insert statement in Python?如何在 Python 中编写正确的 MySQL Insert 语句?
【发布时间】:2019-12-09 14:12:12
【问题描述】:

我正在尝试从 Python 将两列数据插入到 MySQL 表中。我猜我的插入语句是真的。但我仍然收到 1064 错误代码。

这适用于 MySQL 服务器版本 8.0.12 和 Python 3.7。我曾尝试更改插入动态变量的不同方法。

#alter is the data value read from serial port

sql="select * from stds"
cur.execute(sql)
records=cur.fetchall()
if cur.rowcount>0:
   print('Number of rows - ',cur.rowcount)
else:
   print('No data in table')
for row in records:
   print(row)
if row[1]==alter:
    print("Student exists : ",row[1])
    date = datetime.datetime.now()
    print(type(date))
    ins = (alter, date)
    sql = "Insert into 'attendance' ('stdid', 'dt') VALUES (%s,%s)"
    cur.execute(sql, ins)
    cnn.commit()
    print('Sucessfully Stored the Record')
    #success(alter)
    break
else:
    print("Student doesn't exist")

我收到此错误消息 错误:

mysql.connector.errors.ProgrammingError: 1064 (42000): 你的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取在 ''attendance' ('stdid', 'dt') VALUES ('FE0070E83D5B','2019-08-01 09:09:06.162304'' 附近使用的正确语法第 1 行

我期待这些读取标签值被成功插入。

【问题讨论】:

    标签: python mysql python-3.x mysql-workbench mysql-python


    【解决方案1】:

    MySQL(以及大多数其他风格的 SQL)中的标识符(例如列名和表名)不带单引号。在 MySQL 的情况下,它们不带引号、双引号或反引号。试试这个版本:

    sql = "INSERT INTO attendance (stdid, dt) VALUES (%s, %s)"
    ins = (alter, date)
    cur.execute(sql, ins)
    cnn.commit()
    

    【讨论】:

    • 谢谢!通过这样做解决 sql = "INSERT INTO出席(stdid, dt) VALUES (%s, %s)"
    猜你喜欢
    • 1970-01-01
    • 2011-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-18
    • 2018-09-25
    相关资源
    最近更新 更多