Python 3.4使用MySQLdb将表,列和值作为变量传输

时间:2015-09-12 12:11:32

标签: python python-3.x mysql-python

我正在使用Python 3.4

我有这段代码:

import MySQLdb

table = "my_table"
columns = ("column1", "column2")
values = ("value1", "value2")

conn = MySQLdb.connect (host = "localhost",
                       user = "user",
                       passwd = "password",
                       db = "my_database")

cursor = conn.cursor()

# execute an insert
cursor.execute("INSERT INTO my_table column1, column2 VALUES (value1, value2)")

cursor.commit()
cursor.close()
conn.close()

问:如何将表名,列和值全部作为变量传递?

我想做这样的事情:

sql = "INSERT INTO %s %s VALUES %s" % (my_table, columns, values)
cursor.execute(sql)

1 个答案:

答案 0 :(得分:0)

由于execute方法将转义字符串,因此您必须将其作为两步过程执行。

sql = "INSERT INTO {} ({}) VALUES ({})".format(table, ','.join(columns), ','.join('[%s]' * len(columns)))
# Generates: INSERT INTO my_table (column1,column2) VALUES (?,?)
cursor.execute(sql, values)