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

dzjeubhm  于 2023-10-23  发布在  SQLite
关注(0)|答案(1)|浏览(108)

我很难理解为什么我的代码在访问数据库时会产生两次查询输出。本质上,我希望我的查询查找今天的日期是否存在于数据库中,并将其与作为记录时间戳的一部分的booked_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
);
jckbn6z7

jckbn6z71#

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))

尝试逐块复制和粘贴。

相关问题