【问题标题】:Unable to get the right syntax for sql query in python无法在 python 中获得正确的 sql 查询语法
【发布时间】:2021-09-17 09:47:11
【问题描述】:

我希望将数据插入其中的字段成为一个变量。尽管有很多关于通过变量传递 VALUES 的问题,但传递列名的问题并不多。

ppg = [22.6]
import mysql.connector


mydb = mysql.connector.connect(host="localhost",
                            user="root",
                            password="#########",
                            database="#########")
mycursor = mydb.cursor()


    
command = (
"INSERT INTO table1({t_dot}) where id = 2"
"VALUES(%s)"
)

data = (float(ppg))

mycursor.execute(command.format(t_dot = 'Stats 1 Column'),data)

mydb.commit()

mycursor.close()

mydb.close()  

数据库有一个 id 列,它也用作主键。

我正在接受

ProgrammingError:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册以了解正确的语法使用

【问题讨论】:

  • @don'ttalkjustcode 的意思是,您没有正确格式化 command() 函数内的字符串。如果您希望它的格式正确,则必须在字符串前面加上 f 或在后面加上参数 .format

标签: python mysql


【解决方案1】:

MYsql等rdms没有insertWhere

一个insert只插入一行,它没有条件只要涉及到的所有规则都符合

你能做什么

ppg = [22.6]
import mysql.connector


mydb = mysql.connector.connect(host="localhost",
                            user="root",
                            password="#########",
                            database="#########")
mycursor = mydb.cursor()


    
command = (
"INSERT INTO table1(`{t_dot}`) VALUES (%s)"
)

data = (float(ppg),)

mycursor.execute(command.format(t_dot = 'Stats 1 Column'),data)

mydb.commit()

mycursor.close()

mydb.close()

这仅在所有表的其他列具有默认值或为 auto_increment 时才有效,否则 mysql 将出错

对于更新,您还需要像以前一样替换列

command = (
"UPDATE table1 SET `{t_dot}` =  %s WHERE id =  %s"
)

data = (float(ppg),2)

mycursor.execute(command.format(t_dot = 'Stats 1 Column'),data)

【讨论】:

  • 谢谢。这让我意识到即使字段为空,我也必须使用更新语句。我现在就试试。
  • 我使用了这个插入语句command = ("update table1 set %s= %s where id=%s;" )。其他变量工作正常,但我无法让列名工作,因为它的名称中有一个空格(stats 1 列)。我尝试使用逗号、双逗号和反引号,但语法不正确。 data = ('Stats 专栏', ppg, 2) mycursor.execute(command,data)
  • colum snames can't be replace 你需要制作与插入命令中相同的字符串格式
  • 谢谢。我能够让它工作。
【解决方案2】:

您的insert 查询语句错误。

插入选择: https://dev.mysql.com/doc/refman/8.0/en/insert-select.html

如果你想选择一个/多个值,你可以做到:

INSERT INTO table1(t_dot)  ( select t_dot 
                             from table1 
                             where id = 2) ;

或者,如果您尝试仅插入记录 2

INSERT INTO table1(t_dot) values(2);

【讨论】:

猜你喜欢
  • 2016-09-05
  • 1970-01-01
  • 2017-07-15
  • 2017-07-26
  • 1970-01-01
  • 2022-11-16
  • 2021-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多