python-3.x - 如何在python中将变量插入到sqlite数据库中?

标签 python-3.x sqlite

我的代码似乎运行良好,没有任何错误,但它只是创建了一个没有任何内容的空数据库文件,无法弄清楚我在这里做错了什么。

import sqlite3 as lite
import sys
con = lite.connect('test43.db')

def create_db():
    with con:
        cur = con.cursor()
        cur.execute("DROP TABLE IF EXISTS Contacts")
        cur.execute("CREATE TABLE Contacts (First Name TEXT, Last Name TEXT, Phone TEXT, Email TEXT);")
        cur.execute("INSERT INTO Contacts VALUES (?, ?, ?, ?);", (firstname, lastname, phone, email))
        cur.commit()

#Get user input
print ('Enter a new contact')
print ('')
firstname = input('Enter first name: ')
lastname = input('Enter last name: ')
phone = input('Enter phone number: ')
email = input('Enter Email address: ')

createnewdb = input('Enter 1 to create new db: ')
if createnewdb == 1:
    create_db()
else:
    sys.exit(0)

最佳答案

我发现这个插入变量的例子非常有用。

c.execute("SELECT * FROM {tn} WHERE {idf}={my_id}".\
        format(tn=table_name, cn=column_2, idf=id_column, my_id=some_id))

这是教程的链接。 http://sebastianraschka.com/Articles/2014_sqlite_in_python_tutorial.html

关于python-3.x - 如何在python中将变量插入到sqlite数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19759349/

相关文章:

delphi - 将数据库复制到受限客户端

mysql - 有没有办法用 django 项目运行 python 脚本?

php - 在 Python 中使用 flask 进行 Hmac 验证(在 PHP 和 RUBY 中有引用)

java - SimpleCursorAdapter 无法在 ListActivity 中工作,日志中没有错误

android - 已达到数据库的已编译 sql 语句缓存的最大大小

python - SQLAlchemy 不存在于子选择上?

sqlite - 如何在SQLite中将BLOB数据设置为Nothing或NULL

python-3.x - python3 - 没有名为 'html5lib' 的模块

Python 无法使用 Selenium 识别表格单元格中的文本

python - 为[字符串]/[列表中的项目]赋值