简体   繁体   English

使用current_user的SQL查询不会过滤结果

[英]SQL query using current_user doesn't filter results

The following query retrieves every reservation in the database, but I only want to get the reservations that the current user made. 以下查询检索数据库中的每个保留,但是我只想获取当前用户所做的保留。 When I run the query in the mysql command line, it works. 当我在mysql命令行中运行查询时,它可以工作。 Why isn't this working in my app? 为什么这在我的应用程序中不起作用?

from flaskext.mysql import MySQL
from flask.ext.login import LoginManager
from flask_login import current_user

...

db = MySQL()
db.init_app(app)

...

cur = db.connect().cursor()
cur.execute("SELECT ReservationID FROM Reservation WHERE user_name=" + "'" + current_user + "';")
reservation_instance = cur.fetchall()

current_user is a User instance. current_user是一个User实例。 You can't just add it to a string, you need to use it's username (assuming you called the attribute "username"). 您不能只将它添加到字符串中,而是需要使用它的用户名(假设您将其称为“用户名”属性)。

You are currently open to SQL injection attacks. 您目前可以接受SQL注入攻击。 Never try to insert parameters into a query string yourself. 切勿尝试自己将参数插入查询字符串。 Always use parameterized queries, which lets the driver do the work of building, quote, and escape the query properly. 始终使用参数化查询,这使驱动程序可以正确地进行构建,引用和转义查询的工作。

cur.execute('SELECT ReservationID FROM Reservation WHERE user_name=?', [current_user.username])

The placeholder character (I used ? in the example) depends on the driver. 占位符(在示例中使用? )取决于驱动程序。 Consider using SQLAlchemy , which normalizes this sort of thing and is much more powerful. 考虑使用SQLAlchemy ,它可以规范这种事情并且功能更强大。 There is the Flask-SQLAlchemy to make integration with Flask easier as well. Flask-SQLAlchemy也使与Flask的集成变得更加容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM