【问题标题】:How to insert variable to mysql database with python? "You have an error in your SQL syntax"如何使用python将变量插入mysql数据库? “您的 SQL 语法有错误”
【发布时间】:2019-10-09 12:44:33
【问题描述】:

我正在尝试使用 python 将一个变量插入 mysql 数据库。但我有语法错误..你能帮帮我吗? :)

import mysql.connector
    from mysql.connector import Error
    from mysql.connector import errorcode

    try:
        connection = mysql.connector.connect(host='localhost',
                                         database='Xiaomi_Temp',
                                         user='user',
                                         password='pass')
        cursor = connection.cursor()
        mySql_insert_query = """ INSERT INTO Temp_test (batt) VALUES (%d) """
        recordTuple = (batt)
        print(batt)
        cursor.execute(mySql_insert_query, recordTuple)


        connection.commit()
        print("Record inserted successfully into table")
        cursor.close()

    except mysql.connector.Error as error:
        print("Failed to insert record into table {}".format(error))

    finally:
        if (connection.is_connected()):
            connection.close()
            print("MySQL connection is closed")

我有变量 batt,它有整数值。 我的输出是:

Failed to insert record into table 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '%d)' at line 1
MySQL connection is closed

【问题讨论】:

  • %d 在 Python 中的字符串中用于格式化字符串以将 %d 替换为十进制值 - 例如,以下内容应该有效:"""INSERT INTO Temp_test (batt) VALUES (%d) """ % 12345% 12345 在end 告诉 python 用12345 替换%d)。有关 python 字符串格式化的快速教程:learnpython.org/en/String_Formatting(请注意,此方法已弃用,首选str.format()

标签: python mysql mysql-python


【解决方案1】:

由于在执行查询时整个查询需要采用字符串格式,所以应该使用 %s 而不是 %d ,可以如下完成,

         mySql_insert_query = """ INSERT INTO Temp_test (batt) VALUES (%s) """
         recordTuple = (batt)
         print(batt)
         cursor.execute(mySql_insert_query, recordTuple)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 2019-08-25
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    • 1970-01-01
    相关资源
    最近更新 更多