我目前正在修复一种方法,该方法用于通过用户提交的数据进行查询,并通过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)
答案 0 :(得分:1)
您可以使用SQLAlchemy通过Python构建查询。
对于您的代码,即使只有一个参数,第二个参数也必须是参数的元组。
incident_rows = databaseInsert2("SELECT * FROM incident_history where incident_number=?", (incidentkey,))