Python MYSQLdb如何执行不同参数的insert

Python MYSQLdb how to execute insert with different parameters

如何使用不同的参数执行 mysqldb 插入? 这个例子说:

add_employee = ("INSERT INTO employees "
               "(first_name, last_name, hire_date, gender, birth_date) "
               "VALUES (%s, %s, %s, %s, %s)")

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

cursor.execute(add_employee, data_employee)

我想做的是

cursor.execute("INSERT INTO %s (%s) VALUES (%s)", ('animals', 'name', 'fox'))

但是我得到一个错误

MySQL Error [1064]: 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 ''animals' ('name') VALUES ('fox')' at line 1

我知道 MYSQLdb 的格式化程序工作不正常,有没有办法解决这个问题?而且,是否有可能做这样的事情

cursor.execute("INSERT INTO %s (%s) VALUES (%s)", ('animals', ('name','color'), ('fox', 'orange'))

编辑:请不要假设所有插入的数据都是字符串来做出回答。我还希望能够通过这些查询传递 BLOB 数据

imageofafox = open('fox.jpg', 'rb').read()
sql = "INSERT INTO %s (%s) VALUES (%s)"
cursor.execute(sql, ('animals', 'name, picture', ('fox', imageofafox)))

// 编辑:那是为了 java mysql 东西

您的数据类型错误,数据元组中需要字符串或数值类型。

 //data_employee = ('Geert', 'Vanderkelen', tomorrow, 'M', date(1977, 6, 14))
 data_employee = ('Geert', 'Vanderkelen', 'no idea what tomorrow was', 'M', 'date(1977, 6, 14)')

cursor.execute 将自动引用所有给定的参数,因此您的查询最初无法正常工作,因为 table 引用的名称和字段名称:)

只有当你使用 pythons 内置 % 而不是 , 时,你才应该将你的值包装在 ' 中以确保:

cursor.execute("INSERT INTO %s (%s) VALUES (%s)" % ('animals', 'name', "'fox'"))

如果您想包含多个字段和值,请记住您将它们作为三个字符串传递(数字和其他值也会自动引用 mysql 将处理数据类型):

cursor.execute("INSERT INTO %s (%s) VALUES (%s)" % ('animals', 'name, color', "'fox', 'orange'"))

您可以使用 print 和 %

测试结果
print "INSERT INTO %s (%s) VALUES (%s)" % ('animals', 'name, color', "'fox', 'orange'")

据我所知,您不能将数组作为单个参数传递给执行,只能传递参数列表,因此 ('animals', ['name', 'color'], ... 将不起作用!

这是一个完整的脚本,用于测试和弄清楚为什么它在您的环境中不起作用,因为它确实在我的环境中起作用:

import mysql.connector

connection = mysql.connector.connect(user='root', password='', host='127.0.0.1', database='test')
cursor = connection.cursor()
sql = "INSERT INTO %s (%s) VALUES (%s)"
arg = ('animals', 'name', "'fox'")

cursor.execute('set profiling = 1')
try:
    cursor.execute(sql % arg)
    connection.commit()
except:
    cursor.execute('show profiles')
    for row in cursor:
        print(row)
    raise

connection.close()

说明:如果您使用cursor.execute(sql, args),那么该函数将自动引用所有值。由于您的 SQL 不仅包含 %s 值,还包含 table 名称和字段名称,因此您不能让它们被自动引用,否则 SQL 将失败。如果您使用 cursor.execute(sql % args),那么您必须自己将引号添加到您的值中,但您的查询不会失败,因为 table 名称和字段名称未被引用。

你可以用这个作为你的例子,你的例子是有效的。

add_animals = ("INSERT INTO %s "
                 "(%s) "
                 "VALUES (%s)") 
data_animals = ('animals', 'name', 'fox')
cursor.execute(add_animals, data_animals)

确保使用commit()

将数据提交到数据库