如何在SQLITE SELECT语句中使用python变量

2024-10-01 15:47:31 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我试图在SQL语句中使用python生成的本地变量,但得到错误sqlite3.OperationalError:unrecognized token:“1AM”

    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()

Tags: fromreaddbifconnsqlite3elseint
1条回答
网友
1楼 · 发布于 2024-10-01 15:47:31

正如在注释中提到的,您永远不应该使用字符串操作将变量值插入到SQL查询中,否则您就容易受到SQL injection的攻击。实现您要做的事情的安全方法是将值作为参数传递给您的SQL引擎,这将为您完成所有必要的转义。在你的情况下,这样的方法应该有效:

params = (schchoice, schchoice2)
c.execute("SELECT FName,LName, monstarthour, monendhour FROM MondayHours WHERE monstarthour = ? AND monendhour = ?", params)

相关问题 更多 >

    热门问题