python - SQLite 在插入查询中使用变量
问题描述
我正在尝试制作一个 python SQLite GPA Calculator 项目,我希望能够在其中使用用户输入并将用户给出的值插入到 SQLite 表中。我已经想出了如何插入查询,但我想知道如何在 SQLite 插入中使用 python3 中的变量。我似乎找不到任何适用于我的代码的解决方案,因此非常感谢您的帮助!
import sqlite3
try:
sqliteConnection = sqlite3.connect("SQLite_Python_Test.db")
sqlite_query_create_table = '''CREATE TABLE gpa_calc_users_test(
id INTEGER PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
password TEXT NOT NULL,
gpa_sem1 REAL,
gpa_sem2 REAL);'''
sqlite_query_insert = '''
INSERT INTO gpa_calc_users_test
(id, username, password, gpa_sem1, gpa_sem2)
VALUES
(1,'test', 'blablabla', 3.7, 3.5 )
'''
cursor = sqliteConnection.cursor()
sqliteConnection.commit()
print("Connected to sqlite Successfully")
cursor.execute(sqlite_query_create_table)
sqliteConnection.commit()
print("Table created Successfully")
cursor.execute(sqlite_query_insert)
sqliteConnection.commit()
print("Query inserted Successfully")
cursor.close()
except sqlite3.Error as error:
print("Error while creating a table")
finally:
if(sqliteConnection):
sqliteConnection.close()
print("SQLite connection closed")
解决方案
You may use a prepared statement for your insert, and then bind variables to it:
params = (1, 'test', 'blablabla', 3.7, 3.5,)
sql = """INSERT INTO gpa_calc_users_test
(id, username, password, gpa_sem1, gpa_sem2)
VALUES (?, ?, ?, ?, ?)"""
cursor.execute(sql, params)
推荐阅读
- swift - 我在 CollectionViewCell 中的回调无法正常工作
- javascript - jQuery DataTable 副本不接受输入值
- javascript - 文本节点对应的 instanceof 目标是什么?
- javascript - Angular 使用 ng5-slider 时如何防止页面刷新
- javascript - 对 JS 引擎如何运行 Promise 感到困惑?
- javascript - 下一个 js 映射与门户
- html - 来自外部精灵文件的 SVG
- azure-resource-manager - 创建函数应用程序并通过代码而不是容器发布时是否需要 Linuxfxversion
- python - altair_saver 在循环期间停止:WebDriverException:消息:未知错误:调用函数结果必须是字典
- r - 有没有办法直接使用链接在 RStudio 中运行保存的 bigquery?