2013-07-17 59 views
1

我在Python中创建查询以使用MySQL填充本地数据库中的行。 我的变量product是一个元组,它包含33个值。我想将所有这些值添加到名为roottable(我在dbForge中创建)中列出的适当列中。我得到了一行con.execute()错误:从Python插入到行中到MySQL

TypeError: not all arguments converted during string formatting 

不知道我在做什么错。我正在使用与SQlite相同的语法。 这里是我的代码:

connection = msql.connect(host = 'localhost', user = 'me', passwd = 'password', db = 'TESTDB') 

with connection: 
     for product in list_product: 
       #Get a tuple of standardized informtaion to store in table 
       product = normalize_table_entry(product) 
       con = connection.cursor() 
       con.execute('INSERT INTO roottable VALUES (?,?,?,?,?,?,?,?,?,\ 
          ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)', product) 

      #connection.commit() 

回答

2

是否使用MySQLdb?与sqlite3不同,MySQLdb使用%s作为参数标记,而不是?。所以,在这种情况下,尝试

sql = 'INSERT INTO roottable VALUES ({})'.format(','.join(['%s']*33)) 

connection = msql.connect(host = 'localhost', user = 'me', 
          passwd = 'password', db = 'TESTDB') 

sql = 'INSERT INTO roottable VALUES ({})'.format(','.join(['%s']*33)) 
with connection: 
    for product in list_product: 
     #Get a tuple of standardized information to store in table 
     product = normalize_table_entry(product) 
     con = connection.cursor() 
     con.execute(sql, product) 
     #connection.commit() 

表达','.join(['%s']*33)是最好的看一个小例子理解:

In [25]: ['%s']*3 
Out[25]: ['%s', '%s', '%s'] 

In [26]: ','.join(['%s']*3) 
Out[26]: '%s,%s,%s' 
+0

是的,我使用MySQLdb的。 '%s'是否将值转换为字符串?或者值可以是任何类型?如果你不介意,你能解释'['%s'] * 33' –

+1

'product'中的值可以是任何类型。数据库适配器应处理转换并将值引用到字符串,然后将其传递给MySQL服务器。 '['%s'] * 33'评估为33个项目的列表,每个项目都是字符串“%s”。通常,将一个列表乘以一个整数“n”,会生成一个列表,其中包含n个原始列表的浅度副本。在交互式会话中试试看看! – unutbu

+0

所以当你做'','。join(['%s'] * 33)',你的原始列表是一个元素,你创建了第一个元素的33个副本来定义一个新的列表? –