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

时间:2018-11-22 00:40:39

标签: 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)

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

"insert into mytable values (\\'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): 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 '' at line 1

这是什么意思?我什至没有''的值

编辑

在调查时,我发现_executed的{​​{1}}属性看起来像这样

cursor

为什么在执行查询的查询中仍然还有'insert into dev_test_storage values (\\'val1\\', \\'val2\\')'

这是create table语句

\\

1 个答案:

答案 0 :(得分:2)

请参见以下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

  

由于默认情况下,Connector / Python关闭了自动提交功能,因此MySQL 5.5   和更高版本默认使用事务性InnoDB表,它是   使用连接的commit()提交更改所必需   方法。您也可以使用rollback()方法进行回滚。

编辑:

我不确定您为什么仍然存在查询转义不正确的问题,我已尽可能详细地复制了您的条件,并且效果很好:

表格:

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)