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

时间:2015-03-31 17:16:49

标签: python insert mysql-python

如何使用不同的参数执行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)))

3 个答案:

答案 0 :(得分:0)

//编辑:那是为了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)')

答案 1 :(得分:0)

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

只有当你使用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'")

据我所知,你不能将数组作为单个参数传递给execute,只能传递一个参数列表,所以('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,还包含表名和字段名,因此您不能自动引用它们,否则SQL将失败。如果您使用cursor.execute(sql % args),那么您必须自己将引号添加到您的值中,但您的查询不会失败,因为未引用表名和字段名称。

答案 2 :(得分:0)

如果您的示例正在运行,您可以将此作为示例。

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

确保使用commit()

将数据提交到数据库