使用 virtualenv 与 python3、Flask 和 sqlite3 从一个非常基本的网页查询数据库。我无法插入主页字段中输入的数据。 /what_the_f
页面一直显示“失败”。我究竟做错了什么?我怀疑 try:cursor.excecute
但我不知道为什么这不起作用以及如何修复它,以便将 home.html 页面中输入的文本和整数插入到数据库。
数据库初始化文件:
import sqlite3
connection = sqlite3.connect('database.db')
connection.execute('CREATE TABLE movies (title TEXT, rating INTEGER)')
connection.close()
手动创建的数据库:
(venv) 3 月 7 日星期二 18:42:38$ python initdb.py
Python 脚本:
from flask import Flask, render_template, request
import sqlite3
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
@app.route('/what_the_f', methods = ['POST'])
def movie():
connection = sqlite3.connect('database.db')
cursor = connection.cursor # <-------------- LOOKIE THERE!
title = request.form['title']
rating = request.form['rating']
try:
cursor.execute('INSERT INTO movies (title,rating) VALUES (?,?)', (title,rating))
connection.commit()
message = "success"
except:
connection.rollback()
message = "failure"
finally:
connection.close()
return message
/templates/home.html 文件:
<!DOCTYPE html>
<html>
<head>
<title>WTF? TEST</title>
</head>
<body>
<h1>WTactualF??</h1>
<form action="/what_the_f" method="POST">
<input name="title" />
<input name="rating" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
我刚刚收到 Flask 服务器的这份报告:
127.0.0.1 - - [2017年3月7日18:53:02]“POST/what_the_f HTTP/1.1”200 -
在 Debug模式下运行 Flask,当我退出服务器时我得到这个:
操作系统错误:[Errno 9] 错误的文件描述符
最佳答案
天哪...找到了。我有
cursor = connection.cursor
它当然应该是
cursor = connection.cursor()
...我现在会羞愧地躲起来。请不要看着我。
关于python-3.x - Flask sqlite3 INSERT失败,没有错误信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42660526/