使用参数创建MySQL表时的TypeError

时间:2016-06-27 12:50:09

标签: python mysql

这个执行语句或我传入它的列表有问题。

我一直在:

Traceback (most recent call last):
  File "/Users/Hardway/test_package/sqltest5.py", line 12, in <module>
    cur.execute(create_table, ('userid', 'age_of_account', 'number_of_friends', 'DA_MA', 'user_quality'))    
  File "/Library/Python/2.7/site-packages/MySQL_python-1.2.4b4-py2.7-macosx-10.11-intel.egg/MySQLdb/cursors.py", line 184, in execute
    query = query % db.literal(args)
TypeError: not all arguments converted during string formatting

我现在尝试了所有内容(强制元组,字符串中有3种类型的param变量等)并且可以使用一些帮助。我错过了什么?

import MySQLdb as MS
db1 = MS.connect(host="localhost", user="yosef",passwd="yosef", db ='test2')

cur = db1.cursor()

header = ('userid', 'age_of_account', 'number_of_friends', 'DA_MA', 'user_quality')
drop_table = "DROP TABLE IF EXISTS Users"
create_table = """Create table Users ({0} int, {1} int, {2} int, {3} float, {4} varchar(10))"""

try:
    cur.execute(drop_table)
    cur.execute(create_table, header,)    

    db1.commit()

except MS.Error, e:
    print "That failed"
    print e.args[0], e.args[1]
    db1.rollback()

finally:
    db1.close()

2 个答案:

答案 0 :(得分:1)

您无法将列名作为查询参数传递给cursor.execute()。您必须使用字符串formatting将它们插入到查询中:

create_table = ("CREATE TABLE Users ({} INT, {} INT, {} INT, {} FLOAT,"
                "{} VARCHAR(10))".format(*header))
cur.execute(create_table) 

当然,您需要非常小心header不包含用户输入。

答案 1 :(得分:1)

您可以在MySQLCursor.execute中传递,但不能传递列名称。因此,请使用str.format

create_table = "Create table Users ({0} int, {1} int, {2} int, {3} float, {4} varchar(10))".format(*header)
cur.execute(create_table)

请注意,与*一起使用时,您需要str.format使用expand the tuple