使用current_user.email在Python中进行SQLITE3查询



我需要根据一个条件查询在SQLite中提取一个名为records的表的行,该条件查询只选择与电子邮件列=current_user.email的值匹配的记录。current_user是当前登录用户的代理,所以我希望该表过滤只显示适用于该用户的记录的记录。

rows = c.execute("select * from records where email = current_user.email").fetchall()

解析current_user.email的值没有问题。我可以打印它,它会显示电子邮件。问题在于查询的方式和我实现它的方式,没有过滤记录。然而,当我用引号中的实际电子邮件id替换current_user.email时,例如";xyz@xyz.com&";,它能完美过滤。因此,我的问题是,如何根据另一个变量的值(此处:email=current_user.email(过滤Sqlite列,而不是根据email="xyz@xyz.com

在sql语句中使用?占位符,然后将您要查找的特定值作为额外参数传递。

rows = c.execute("select * from records where email = ?", [current_user.email]).fetchall()

您需要将变量的内容添加到字符串中。现在,您的SQL驱动程序只看到";从记录中选择*,其中email=user.email">

下面的代码应该会有所帮助。

rows = c.execute("select * from records where email = %(username)", {"username": current_user.email}).fetchall()

易受SQL注入攻击的错误代码。

rows = c.execute("select * from records where email = {}".format(current_user.email)).fetchall()

感谢约翰·戈登指出这一点。

最新更新