简体   繁体   English

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

[英]python + sqlite, insert data from variables into table

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.也许有人可以指出我正确的方向。

You can use ?你可以用? to represent a parameter in an SQL query:表示 SQL 查询中的参数:

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

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

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

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

OR或者

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

As you are inserting values to all available fields, its okay not to mention columns name in insert query当您向所有可用字段插入值时,可以不在插入查询中提及列名

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

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