Search code examples
pythonmysqlmysql-connector-python

Syntax error with floats when inserting into a table


Im trying to insert data into a table using python but im getting a syntax error. Here is my table format.

mycursor.execute("""CREATE TABLE workers (
                 `ID` int(5) NOT NULL AUTO_INCREMENT,
                 ` x` FLOAT NOT NULL,
                 ` y` FLOAT NOT NULL,
                 `z` FLOAT NOT NULL,
                 `Acc` int NOT NULL,
                 `Datasource` char(3) NOT NULL,
                 `Datatype` int(5) NOT NULL,
         PRIMARY KEY (`ID`))""")

The table code works fine

Here is the data im trying to insert into those tables

mycursor.execute("""INSERT INTO workers VALUES
(1,\ 
1.2720693 ,\
6.583606 ,\
6.8299093 ,\
3 ,\
"Acc" ,\
1)""")

This is the error im getting

mysql.connector.errors.ProgrammingError: 1064 (42000): 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 '\ 
1.2720693 ,6.583606 ,6.8299093 ,3 ,"Acc" ,1)' at line 2

Solution

  • The error you are getting back from the server is telling you the backslashes are are the problem.

    mycursor.execute("""
                     INSERT INTO workers VALUE (1,                    
                     1.2720693,
                     6.583606,
                     6.8299093,
                     3,
                     "Acc",
                     1)
                     """)
    

    Triple strings in python are designed for multiline strings so you don't need to handle line continuations with backslashes. You also have 7 field values in your INSERT statement but you only need 6 as ID column is auto-incrementing.