flask sqlite数据库错误

时间:2015-11-05 08:22:55

标签: python sqlite flask

我是烧瓶网站开发的新手,我正在使用sqlite来存储电子邮件地址 我的代码是

from flask import *
import sqlite3


app = Flask(__name__)

conn = sqlite3.connect("emails.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE email_addresses1 ( email TEXT );")

@app.before_request
def before_request():
    g.db = sqlite3.connect("emails.db")

@app.teardown_request
def teardown_request(exception):
     if hasattr(g, 'db'):
        g.db.close()

@app.route('/')
def hello():
    return render_template('index.html')

@app.route('/signup', methods = ['POST'])
def signup():
    email = request.form['email']
    print("The email address is '" + email + "'")
    g.db.execute("INSERT INTO email_addresses VALUES (?)", [email])
    g.db.commit()
    return redirect('/')

@app.route('/emails.html')
def emails():
    email_addresses = g.db.execute("SELECT email FROM  email_addresses").fetchall()
    return email_addresses

if __name__ == "__main__":
    app.run(debug=True)   

我收到以下错误消息

cursor.execute("CREATE TABLE email_addresses1 ( email TEXT );")
sqlite3.OperationalError: table email_addresses1 already exists

1 个答案:

答案 0 :(得分:2)

仅在表格不存在的情况下创建表格 - 将IF NOT EXISTS添加到create table语句中。

from flask import *
import sqlite3


app = Flask(__name__)

conn = sqlite3.connect("emails.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS email_addresses1 ( email TEXT );")
...

查看SQLite doc