python:无法格式化sql查询字符串

t98cgbkg  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(486)

我想创建一个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 的属性 cursor 看起来像这样

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

为什么我还有 \\ 在执行的查询中?
下面是create table语句

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

dzhpxtsq1#

请看mysql connector python文档中有关insert的以下示例。不要使用 format 对于准备好的语句参数,将它们作为第二个参数传递给 execute . 该示例显示了以元组和dict形式传递数据:

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关闭了autocommit,mysql 5.5及更高版本默认使用事务性innodb表,因此有必要使用connection的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)

相关问题