简体   繁体   中英

SQL syntax error when try insert into by python

I have the following table in my database:

create table tt (
id varchar(20),
hora varchar(20),
preco varchar(20),
qtde varchar(20),
cpa varchar(20),
vda varchar(20),
agressor varchar(20)
);

I put them all like varchar (30) because my head was too white with the mistakes they were making.

even with all fields like varchar (30) I am not able to insert into the following 7 values via python

19928 12:53:34 4.049,00 5 107 308 Comprador

(19928, "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 ':53:34, 4.049,00, 5, 107, 308, Comprador)' at line 1")

my command to insert into is the following:

c.execute("INSERT INTO tt VALUES ({}, {}, {}, {}, {}, {}, {})".format(id_, hora, preco, qtde, cpa, vda, agressor))
conn.commit()

could also assist me in what types of variables to use to create the table? (int, varchar (20), float)?

You should be using a prepared statement here, which would likely also resolve your current errors:

cursor = conn.cursor(prepared=True)
sql = """INSERT INTO tt (id, hora, preco, qtde, cpa, vda, agressor)
         VALUES (%s, %s, %s, %s, %s, %s, %s)"""
cursor.execute(sql, (id_, hora, preco, qtde, cpa, vda, agressor,))
conn.commit()

Using this approach, you let Python/MySQL worry how to properly escape your string data with single quotes. Also note that it is best practice to always explicitly list out the target columns for an insert, which I have done above.

Your problem is that your query looks like this:

INSERT INTO tt VALUES (19928, 12:53:34, 4.049,00, 5, 107, 308, Comprador)

which is invalid because of unquoted time and string values, and the comma in one of the numbers. You need to use the prepared statement form:

c = conn.cursor()
c.execute("INSERT INTO tt VALUES (%s, %s, %s, %s, %s, %s, %s)",(id_, hora, preco, qtde, cpa, vda, agressor))
conn.commit()
c.close()

Note that when you change your column data types, to insert 4.049,00 into MySQL as a number you will need to first swap the , and . characters.

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