简体   繁体   English

尝试通过python插入时出现SQL语法错误

[英]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.我把它们都像 varchar (30) 一样,因为我的头太白了,他们犯了错误。

even with all fields like varchar (30) I am not able to insert into the following 7 values via python即使使用 varchar (30) 等所有字段,我也无法通过 python 插入以下 7 个值

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") (19928 年,“您的 SQL 语法有错误;请检查与您的 MySQL 服务器版本相对应的手册,以获取在 ':53:34, 4.049,00, 5, 107, 308, Comprador 附近使用的正确语法)'第 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)? (整数,varchar(20),浮点数)?

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.使用这种方法,您可以让 Python/MySQL 担心如何使用单引号正确转义字符串数据。 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 .请注意,当您更改列数据类型时,要将4.049,00作为数字插入 MySQL,您需要先交换,. characters.人物。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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