2011-05-21 65 views
1

我正在學習python,而且我是新的bie。 我想使用的功能與MySQL和Python和我是個得到錯誤在Python中執行許多錯誤

這是我的腳本

import MySQLdb 
def insert_values(cursor, values): 
    #cursor = self.connection.cursor() 
    cursor.executemany(""" 
     insert into pythontest (name1,name2,name3) 
     values (%s, %s, %s)""", values) 
    cursor.close() 

db = MySQLdb.connect("localhost","root","root","python") 
cursor = db.cursor() 

var1 = ['name1','name2','name3'] 
insert_values(cursor,var1) 

db.close() 

可能有很多錯誤,因爲我正在學習

1)i don't know how can i pass db object in function or passing cusrsor is ok. because i have to call that function many times in for loop

2)is the syntax of values array ok to go in database

錯誤

File "mysql.py", line 10, in insert_values 
    values (%s, %s, %s)""", values) 
    File "build/bdist.linux-i686/egg/MySQLdb/cursors.py", line 216, in executemany 
    File "build/bdist.linux-i686/egg/MySQLdb/connections.py", line 36, in defaulterrorhandler 
_mysql_exceptions.ProgrammingError: not enough arguments for format string 
+0

請指出您看到的錯誤。 – 2011-05-21 09:12:50

+0

我已添加錯誤 – Mahakaal 2011-05-21 09:18:03

回答

1

這是我會怎麼寫(但未經測試):

import MySQLdb 

def insert_values(db, values): 
    cursor = db.cursor() 
    try: 
     try: 
      cursor.execute(""" 
      insert into pythontest (name1,name2,name3) 
      values (%s, %s, %s)""", *values) 
     except: 
      db.rollback() 
      raise 
     else: 
      db.commit() 
    finally: 
     cursor.close() 

db = MySQLdb.connect("localhost","root","root","python") 

vars = ('name1','name2','name3') 
insert_values(db, vars) 

db.close() 

光標開始交易,所以你不想再使用的多個更新相同的遊標,除非他們是一個原子事務的一部分。

+0

我得到這個錯誤TypeError:executemany()只需要3個參數(給定5),也需要用db.rollback – Mahakaal 2011-05-21 09:59:06

+0

來代替cursor.rollback,應該已經檢查過了。但它看起來像你真正需要我們的執行方法。 – Keith 2011-05-21 10:10:17

+0

從值中刪除「*」後,execute方法起作用。但我想知道我需要在代碼中做些什麼來使executemany工作。我只是在學習東西。編輯:executemany也工作,如果我替換'vars = [('name11','name12','name13'),('name21','name22','name23')]'但如果我把星號(*)在*值中,然後我得到相同的錯誤 – Mahakaal 2011-05-21 10:20:48

2
cursor.executemany(""" 
     insert into pythontest (name1,name2,name3) 
     values (%s, %s, %s)""", *values) 
+0

我不知道是誰downvoted這,但它是正確的答案。 OP正在發送一個列表,「* values」將列表解壓縮爲字符串預期的3個值。錯誤消息非常明確。 – dotancohen 2014-01-06 11:47:58