每次运行
INSERT INTO
语句时,都会收到错误。
我用conn试过了,还是不行。我发布了我的代码和错误消息。
请给我一个如何解决这个问题的提示。
我的代码是:
def register():
session.clear()
if request.method == "POST":
if not request.form.get("username"):
return 'must provide username'
elif not request.form.get("password"):
return 'must provide password'
elif not request.form.get("confirmation"):
return 'must provide confirmation'
elif request.form.get("password") != request.form.get("confirmation"):
return 'password does not match'
rows = db.execute("SELECT * FROM users WHERE username = ?", request.form.get("username"))
if len(rows) != 0:
return 'username already exists'
db.execute("INSERT INTO users (username, hash) VALUES (?, ?)", request.form.get("username"), generate_password_hash(request.form.get("password")))
session["user_id"] = rows[0]["id"]
return redirect("/")
else:
return render_template("register.html")
我的桌子是:
CREATE TABLE IF NOT EXISTS "users" (
"id" INTEGER,
"username" text NOT NULL,
"hash" text NOT NULL,
"wateruse" int,
PRIMARY KEY("id" AUTOINCREMENT)
这是一个标准且有效的 Python 示例,说明如何使用给定结构创建表,并向其中插入值,而不指定 id:
import sqlite3
from contextlib import closing
with closing(sqlite3.connect('test.sqlite')) as con:
with closing(con.cursor()) as cur:
cur.execute('''
CREATE TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL, hash TEXT NOT NULL, wateruse INT)
''')
cur.execute('''
INSERT INTO users (username, hash) VALUES (?, ?)
''', ("a", "b"))
con.commit()
您可能还想确保用户或哈希值是唯一的。