简体   繁体   中英

How to insert variable to mysql database with python? “You have an error in your SQL syntax”

I am trying to insert one variable to mysql database with python. But I have syntax error.. Can You help me please? :)

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")

I have variable batt and it has integer value. My output is:

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

As the whole query needs to be in a string format while execution of query so %s should be used instead of %d which can be done as follows,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM