简体   繁体   English

在函数中传递元组

[英]passing a tuple in function

I went through questions but I couldn't figure it out in case of mine 我遇到了问题,但我无法解决

I wrote a function which takes a tuple as a parameter and performs this: 我编写了一个将元组作为参数并执行以下操作的函数:

def add_subject(name_stud, *data):
    c.execute("INSERT INTO " + name_stud + " VALUES (?,?,?,?,?,?,?,?)", 
             data)
    conn.commit()

And I tried calling this function in a class method passing tuple as a parameter but I get error 我尝试在通过元组作为参数的类方法中调用此函数,但出现错误

add_subject(self.page1.student_name, data)

data is the tuple there. 数据就是那里的元组。

and the error is: 错误是:

sqlite3.ProgrammingError: Incorrect number of bindings supplied. sqlite3.ProgrammingError:提供的绑定数量不正确。 The current statement uses 8, and there are 1 supplied. 当前语句使用8,并且提供了1。

And I tried unpacking at the time I am using it, I still got error: 我在使用时尝试打开包装,但仍然出现错误:

def add_subject(name_stud, data):
    c.execute("INSERT INTO " + name_stud + " VALUES (?,?,?,?,?,?,?,?)", 
              *data)
    conn.commit()

error: 错误:

sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type. sqlite3.InterfaceError:错误绑定参数0-可能不受支持的类型。

Answers from other peoples didn't help me. 其他人的回答对我没有帮助。 Any help will be appreciated. 任何帮助将不胜感激。

You've declared the parameter data as positional args, but are passing only a single argument, data . 您已将参数data声明为位置args,但仅传递了一个参数data This means that the final parameter will be (data,) . 这意味着最终参数将是(data,) You need to unpack the tuple on passing in order to populate the positional args. 您需要在通过时打开元组的包装,以填充位置args。

add_subject(self.page1.student_name, *data)

Since you're passing the tuple as a single argument, you shouldn't write *data in the function definition. 由于将元组作为单个参数传递,因此不应在函数定义中写入*data Just declare it as an ordinary function parameter. 只需将其声明为普通函数参数即可。

def add_subject(name_stud, data):
    row = data
    c.execute("INSERT INTO " + name_stud + " VALUES (?,?,?,?,?,?,?,?)", 
             data)
    conn.commit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM