2013-07-17 58 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個副本來定義一個新的列表? –