所以我试图在我的SQL语句中使用在python中创建的本地varibale,但是我得到错误sqlite3.OperationalError:无法识别的令牌:" 1 AM"
if schchoice==int("1"):
schchoice=str("12AM")
elif schchoice == int("2"):
schchoice="1AM"
else:
print("INVALID")
if schchoice2==int("1"):
schchoice=str("12AM")
elif schchoice2==int("2"):
schchoice2="1AM"
else:
print("INVALID")
conn = sqlite3.connect('Employee.db')
c = conn.cursor()
def read_from_db():
c.execute("SELECT FName,LName, monstarthour, monendhour FROM MondayHours WHERE monstarthour ='"+schchoice+"'AND monendhour='"+schchoice2+'"')
#data = c.fetchall()
for row in c.fetchall():
print(row)
read_from_db()
答案 0 :(得分:1)
如评论中所述,您绝不应该使用字符串操作将变量值插入SQL查询中,否则您很容易受到SQL injection的攻击。实现您要做的事情的安全方法是将值作为参数传递给SQL引擎,这将为您执行所有必要的转义。在你的情况下,这样的事情应该有效:
params = (schchoice, schchoice2)
c.execute("SELECT FName,LName, monstarthour, monendhour FROM MondayHours WHERE monstarthour = ? AND monendhour = ?", params)