在python中执行多个命令时出错

在python中执行多个命令时出错,python,mysql,linux,Python,Mysql,Linux,我正在学习python,我是新来的。 我试图使用mysql和python的函数,但我发现了一些错误 这是我的剧本 import MySQLdb def insert_values(cursor, values): #cursor = self.connection.cursor() cursor.executemany(""" insert into pythontest (name1,name2,name3) values (%s, %s, %s

我正在学习python,我是新来的。 我试图使用mysql和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) 我不知道怎样才能通过db 函数中的对象或传递的cussor 可以。因为我不得不这么说 在for循环中多次执行函数

2) 数组值的语法是否正确 进入数据库

错误

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

下面是我将如何写的(但未经测试):


游标启动事务,因此您不希望重复使用同一游标进行多个更新,除非它们是原子事务的一部分。

请指定您看到的错误。我得到此错误类型错误:executemany()正好接受3个参数(给定5个),还需要将cursor.rollback替换为db.rollbackright,应该已选中。但看起来您真正想要的只是execute方法。execute方法在从值中删除“”后工作。但我想知道我需要在代码中做什么才能使ExecuteMay正常工作。我只是在学习。编辑:如果我替换
vars=[('name11'、'name12'、'name13')、('name21'、'name22'、'name23')],执行器也可以工作。
但是如果我将star()放在*值中,那么我会得到同样的错误,它需要一个元组列表来多次应用SQL。不同的签名。我不知道是谁否决了这个,但这是正确的答案。OP正在发送一个列表,
*values
将列表解压为格式字符串所需的3个值。错误消息非常清楚地说明了问题。
cursor.executemany("""
        insert into pythontest (name1,name2,name3)
        values (%s, %s, %s)""", *values)
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()