python + sqlite,将变量中的数据插入表中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4360593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:25:54  来源:igfitidea点击:

python + sqlite, insert data from variables into table

pythonsqlsqlite

提问by steini

I can insert hardcoded values into an SQLite table with no problem, but I'm trying to do something like this:

我可以毫无问题地将硬编码值插入到 SQLite 表中,但我正在尝试执行以下操作:

name = input("Name: ")
phone = input("Phone number: ")
email = input("Email: ")

cur.execute("create table contacts (name, phone, email)")
cur.execute("insert into contacts (name, phone, email) values"), (name, phone, email)

I know this is wrong, and I can't find how to make it work. Maybe someone could point me in the right direction.

我知道这是错误的,我无法找到如何使它起作用。也许有人可以指出我正确的方向。

回答by Mark Byers

You can use ?to represent a parameter in an SQL query:

您可以使用?来表示 SQL 查询中的参数:

cur.execute("insert into contacts (name, phone, email) values (?, ?, ?)",
            (name, phone, email))

回答by pro1991

cur.executemany("insert into contacts (name, phone, email) values (?, ?, ?)", (name, phone, email))

cur.executemany("插入联系人(姓名,电话,电子邮件)值(?,?,?)”,(姓名,电话,电子邮件))