【发布时间】:2018-07-30 19:22:35
【问题描述】:
我目前正在修复一种方法,该方法用于对用户提交的数据进行查询,并通过 SQLITE3 执行数据库操作(例如更新、插入或删除)。
目的是允许接受可选参数,这些参数将引用用户提交的查询变量。如何使用该方法的示例:
incidentkey = request.args.get('incident')
incident_rows = databaseInsert2("SELECT * FROM incident_history where incident_number=?", incidentkey)
我提供的代码有几个问题 - 但是,主要问题是我的查询失败。最初查询由于语法而直接失败,但是现在它似乎返回了一个 None 类型的对象,我已经确认可以在 Sqlite3 中手动访问该项目。
有没有更好的方法来处理可能包含未知数量参数的查询?任何帮助将不胜感激。
def databaseInsert2(query, *args):
try:
conn = sql.connect('db/ccstatus.db')
c = conn.cursor()
c.execute(query, (args))
conn.commit()
c.close()
print("Database Insert: Success")
except sql.Error as e:
print("You have encountered an error while attempting to connect to the database: ", query, args, e)
更新:
我能够使用 *args 作为参数让我的代码按预期工作。我错过了一个没有返回假设结果的关键部分——一旦返回,上面的代码就可以正常工作了。
工作代码示例:
def dbLookup(query, *args):
try:
con = sql.connect('db/ccstatus.db')
con.row_factory = sql.Row
c = con.cursor()
c.execute(query, (args))
con.commit()
rows = c.fetchall()
c.close()
print("Connection Success")
except sql.Error as e:
print("You have encountered an error while attempting to connect to the database: ", query, args, e)
return rows
如何调用此方法的示例:
dbAlter("INSERT INTO systems VALUES (NULL, ?, ?, ?, ?", name, description, urlname, url)
【问题讨论】:
标签: python python-3.x flask sqlite