Python:无法格式化 SQL 查询字符串

标签 python mysql string-formatting pymysql

我想创建一个 SQL 查询字符串并从 python 执行它

import mysql.connector
from mysql.connector import Error


client = mysql.connector.connect(host=sql_host,
                                 port=sql_port,
                                 database=sql_db,
                                 user=os.environ['SQLUSER'],
                                 passwd=os.environ['SQLPASS']
                                 )
try:
    a = "val1"
    b = "val2"
    cursor = client.cursor()
    query = "insert into mytable values ('{}', '{}')".format(a,b)
    print(query)
    cursor.execute(query)

except Error as e:
    print(e)

这不会给我错误,但同时,表中不会插入任何内容。我认为那是因为创建的查询字符串看起来像

“插入 mytable 值 (\\'val1\\',\\'val2\\')”

我什至尝试过 .replace('\\','') 但无法从查询字符串中删除 \\

我做错了什么?

更新:

感谢@cody 的帮助。但现在,我遇到了不同的错误

a = 'val1'
b = 'val2'
query = "insert into mytable values (%s, %s)"
print(query)
cursor.execute(query, (a,b))
client.commit()

现在我明白了

1064 (42000):您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,了解在第 1 行 '' 附近使用的正确语法

这是什么意思?我的值(value)观中甚至没有任何''

编辑

在调查时,我发现 cursor_execulated 属性如下所示

'insert into dev_test_storage values (\\'val1\\', \\'val2\\')'

为什么我执行的查询中仍然有 \\

这是创建表语句

CREATE TABLE IF NOT EXISTS myTable 
(
    col1 varchar(50) not null,
    col2 varchar (100) not null
);

最佳答案

看下面MySQL中的例子connector-python documentation for insert 。不要对准备好的语句参数使用format,而是将它们作为第二个参数传递给execute。该示例显示了将数据作为元组和字典传递:

from __future__ import print_function
from datetime import date, datetime, timedelta
import mysql.connector

cnx = mysql.connector.connect(user='scott', database='employees')
cursor = cnx.cursor()

tomorrow = datetime.now().date() + timedelta(days=1)

add_employee = ("INSERT INTO employees "
               "(first_name, last_name, hire_date, gender, birth_date) "
               "VALUES (%s, %s, %s, %s, %s)")
add_salary = ("INSERT INTO salaries "
              "(emp_no, salary, from_date, to_date) "
              "VALUES (%(emp_no)s, %(salary)s, %(from_date)s, %(to_date)s)")

data_employee = ('Geert', 'Vanderkelen', tomorrow, 'M', date(1977, 6, 14))

# Insert new employee
cursor.execute(add_employee, data_employee)
emp_no = cursor.lastrowid

# Insert salary information
data_salary = {
  'emp_no': emp_no,
  'salary': 50000,
  'from_date': tomorrow,
  'to_date': date(9999, 1, 1),
}
cursor.execute(add_salary, data_salary)

# Make sure data is committed to the database
cnx.commit()

cursor.close()
cnx.close()

此外,您可能需要按照文档所述调用commit

Since by default Connector/Python turns autocommit off, and MySQL 5.5 and higher uses transactional InnoDB tables by default, it is necessary to commit your changes using the connection's commit() method. You could also roll back using the rollback() method.

编辑:

我不确定为什么您仍然遇到查询被不正确转义的问题,我已尽可能接近地复制了您的条件并且工作正常:

表:

MariaDB [pets]> DESCRIBE myTable;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| col1  | varchar(50)  | NO   |     | NULL    |       |
| col2  | varchar(100) | NO   |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+

Python 代码:

import mysql.connector

cnx = mysql.connector.connect(user='cody', password='secret', database='pets')
cursor = cnx.cursor()

a = 'val1'
b = 'val2'

query = "insert into myTable values (%s, %s)"

cursor.execute(query, (a,b))

cnx.commit()

print(cursor._executed)

cursor.close()
cnx.close()

程序成功运行并按预期打印执行的查询:

cody@servo:~$ python mysql-test.py
insert into myTable values ('val1', 'val2')

该行已插入:

MariaDB [pets]> SELECT * FROM myTable;
+------+------+
| col1 | col2 |
+------+------+
| val1 | val2 |
+------+------+
1 row in set (0.01 sec)

关于Python:无法格式化 SQL 查询字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53422394/

相关文章:

php - 从 php 触发 bash 脚本时,服务未执行

java - 如何在 Java 中格式化 Twitter 时间戳?

python - 格式化具有固定长度和空格填充的整数的正确方法

python - python 中的传感器数据日志 csv

python - 如何在 python 中使 print 语句成为一行?

python - 为什么我不能以这种方式实现合并排序

python - 如何在 Tensorflow 中使用逐个事件的权重?

Mysql在select语句中添加变量

mysql - 从具有父子关系的单表创建 mySQL 连接表

.net - 将不受信任的格式字符串传递给 string.Format 是否安全?