Python 代码对数据库执行 SQLite 查询两次

问题描述 投票:0回答:1

我很难理解为什么我的代码在访问数据库时会生成两次查询输出。本质上,我希望我的查询查找数据库中是否存在今天的日期,并将其与作为记录时间戳一部分的 booking_time 日期部分进行比较。如果存在则打印该记录。正如你在下面看到的,我遇到了“双输出”

from flask import request
import sqlite3

def read_query(query):
    con = sqlite3.connect("database.db")
    cur = con.cursor()

    cur.execute(query)
    result = cur.fetchall()
    return result


q1 = """
SELECT email,booked_time,strftime('%Y-%m-%d',booked_time) as 'date'
FROM bookings
WHERE date = DATE('2023-09-04');
"""

print(read_query(q1))

输出

devbox:~/web_app_project$ python3 schedule.py 
[('[email protected]', '2023-09-04 10:00:00', '2023-09-04')]
[('[email protected]', '2023-09-04 10:00:00', '2023-09-04')]

我尝试使用 con.commit() 和 con.close() 方法来解决此问题,但得到了相同的结果。我尝试使用“with”上下文管理器重写,但仍然得到双输出。有人有解决方案吗?我预计只会出现一张记录。

作为 @Daviids 帮助故障排除的一部分:

from flask import Flask, render_template, request
import sqlite3 as sql

app = Flask(__name__)


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


@app.route('/process', methods=['POST'])
def process():
    if request.method == 'POST':
        name = request.form['name']
        email = request.form['email']
        date = request.form['date']
        hour = request.form['hour']
        minutes = request.form['minutes']

        booked_time = (f"{date} {hour}:{minutes}:00")
        with sql.connect("database.db") as con:
            cur = con.cursor()
            cur.execute(
                "INSERT INTO bookings (name, email, booked_time) VALUES (?, ?, ?)",
                (name, email, booked_time))
            con.commit()
            msg = "Record successfully added"
    return msg
    con.close()


if __name__ == '__main__':
    app.run

数据通过网络表单输入。以下是数据库的创建方式。

import sqlite3

connection = sqlite3.connect('database.db')


with open('schema.sql') as f:
    connection.executescript(f.read())

cur = connection.cursor()


connection.commit()
connection.close()

架构文件:

CREATE TABLE bookings (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    email TEXT NOT NULL,
    created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    booked_time TIMESTAMP NOT NULL UNIQUE
);
python sqlite
1个回答
0
投票
import sqlite3

SQLITE_SCRIPT = """
-- Create the bookings table
CREATE TABLE IF NOT EXISTS bookings (
    id INTEGER PRIMARY KEY,
    email TEXT,
    booked_time DATETIME
);

-- Insert some sample data
INSERT INTO bookings (email, booked_time) VALUES
    ('[email protected]', '2023-09-04 10:00:00'),
    ('[email protected]', '2023-09-04 14:30:00'),
    ('[email protected]', '2023-09-05 09:15:00');
"""

def read_query(query):
    con = sqlite3.connect(":memory:")
    # Write the downloaded data into the in-memory database
    con.executescript(SQLITE_SCRIPT)
    cur = con.cursor()

    cur.execute(query)
    result = cur.fetchall()
    return result


q1 = """
SELECT email,booked_time,strftime('%Y-%m-%d',booked_time) as 'date'
FROM bookings
WHERE date = DATE('2023-09-04');
"""

print(read_query(q1))

我在本地尝试过,但没有得到双重打印。 我没有使用 sqlite 文件,而是创建了一个内存数据库,创建表并插入一些数据。你可以尝试一下,看看你是否遇到同样的问题吗?

编辑:如果仍然发生,我只能考虑从 python 解释器内部尝试

开始于

devbox:~/web_app_project$ python3

然后

import sqlite3
SQLITE_SCRIPT = """
-- Create the bookings table
CREATE TABLE IF NOT EXISTS bookings (
    id INTEGER PRIMARY KEY,
    email TEXT,
    booked_time DATETIME
);

-- Insert some sample data
INSERT INTO bookings (email, booked_time) VALUES
    ('[email protected]', '2023-09-04 10:00:00'),
    ('[email protected]', '2023-09-04 14:30:00'),
    ('[email protected]', '2023-09-05 09:15:00');
"""
def read_query(query):
    con = sqlite3.connect(":memory:")
    # Write the downloaded data into the in-memory database
    con.executescript(SQLITE_SCRIPT)
    cur = con.cursor()

    cur.execute(query)
    result = cur.fetchall()
    return result
q1 = """
SELECT email,booked_time,strftime('%Y-%m-%d',booked_time) as 'date'
FROM bookings
WHERE date = DATE('2023-09-04');
"""
print(read_query(q1))

尝试逐块复制和粘贴。

© www.soinside.com 2019 - 2024. All rights reserved.