2013-03-23 51 views
2

我想使用Python MySQLConnector將包含數字的集添加到我的MySQL數據庫中。我可以手動添加數據,但下面的表達式與%s將不起作用。我在這方面嘗試了幾個變種,但文檔中沒有任何變化似乎適用於我的情況。該表已經buildt你可以看到:與%s的Python mysql連接器插入

#Table erstellen: 
#cursor.execute('''CREATE TABLE anzahlids(tweetid INT )''') 

這裏是我的代碼和錯誤:

print len(idset) 
    id_data = [ 
     len(idset) 
    ] 
    print id_data 
    insert = ("""INSERT INTO anzahlids (idnummer) VALUES (%s)""") 
    cursor.executemany(insert, id_data) 
    db_connection.commit() 

"Failed processing format-parameters; %s" % e)
mysql.connector.errors.ProgrammingError: Failed processing format-parameters; argument 2 to map() must support iteration

+0

oops。 Worng表。正確的將是: cursor.execute('''CREATE TABLE anzahlids( idnummer INT)''') 在代碼中它是正確的。 – phibaa 2013-03-23 20:35:30

+0

請發佈idset中的數據示例 – 2013-03-23 20:55:05

+0

idset是一個id列表。這些ID是數字。但是我想將'len(idset)'插入到數據庫中。 – phibaa 2013-03-23 21:17:23

回答

0

以下是我的機器上工作的例子。

import MySQLdb 
db = MySQLdb.connect(host="localhost", user="stackoverflow", passwd="", db="stackoverflow") 
cursor = db.cursor() 
try: 
    sql = 'create table if not exists anzahlids(tweetid int) ; ' 
except: 
    #ignore 
    pass 

sql = ("""INSERT INTO anzahlids (tweetid) VALUES (%s)""") 
data = [1,2,3,4,5,6,7,8,9] 
length = [len(data)] 
cursor.executemany(sql,length) 
db.commit() 

如果idset是一個值,你可以使用

sql = ("""INSERT INTO anzahlids (tweetid) VALUES (%s)""") % len(idset) 
cursor.execute(sql) 
db.commit() 
+0

謝謝,但會產生: 'raise errors.get_exception(packet) mysql.connector.errors.ProgrammingError:1064(42000):您的SQL語法錯誤;請查看與您的MySQL服務器版本相對應的手冊,在'012'附近使用'[100]'''')行 但是我們似乎越來越接近... – phibaa 2013-03-23 20:49:16

+0

我的錯誤...我改變了答案以反映cursor.exe所需的參數類型很多。 – 2013-03-23 20:51:32

+0

現在它是: 'values.append(fmt%self._process_params(params)) TypeError:並非在字符串格式化過程中轉換的所有參數 但是,再次感謝! – phibaa 2013-03-23 20:56:03

3

晚的答案,但我想張貼一些更好的代碼。另外,原來的問題是使用MySQL連接器/ Python。

executemany()的使用是錯誤的。 executemany()方法需要一系列元組,例如[(1,),(2,)]。

手頭的問題,executemany()實際上是沒有用的,執行()應使用:

cur.execute("DROP TABLE IF EXISTS anzahlids") 
cur.execute("CREATE TABLE anzahlids (tweetid INT)") 

some_ids = [ 1, 2, 3, 4, 5] 
cur.execute("INSERT INTO anzahlids (tweetid) VALUES (%s)", 
      (len(some_ids),)) 
cnx.commit() 

而且與MySQL連接器/ Python的(不像MySQLdb的),你必須確保你正在提交。

(對於非德語的說明:'anzahlids'表示'number_of_ids')