Flask
Flask - 根据字符串检查数据库(Flask - Check database against string) python码:
userExists = g.db.execute('SELECT username FROM users WHERE username = ?', [request.form['usr']])if request.form['usr'] == userExists: error = 'Username already exists.'希望代码是不言自明的。 如果没有,我希望注册用户对数据库检查他的名字。 用户名必须是唯一的,因此如果输入到表单中的信息(request.form ['usr'])等于保存到userExists变量的SQL查询的结果,则应抛出错误(error ='Username已存在) 。')。
查询是否返回与用户名匹配的行数而不是用户名的值? 或者逻辑是不正确的。
Code:
userExists = g.db.execute('SELECT username FROM users WHERE username = ?', [request.form['usr']])if request.form['usr'] == userExists: error = 'Username already exists.'Hopefully the code is self-explanatory. If not, I want a registering user to have his name checked against the database. The username must be unique so if the information entered into the form (request.form['usr']) is equal to the result of the SQL query saved to the userExists variable then an error should be thrown (error = 'Username already exists.').
Is the query returning the number of rows matching username instead of the value of username? Or is the logic just incorrect.
最满意答案您可以通过在创建表时将username定义为唯一键来执行此操作。 然后将INSERT放入try ... catch ...块。 如果用户名存在,则抛出异常。
You can do this by defining the username as an unique key when creating table. Then put the INSERT into a try ... catch ... block. If the username exists, an exception will be thrown.