首页 > 解决方案 > 带有 Python 的 Sqlite3 返回额外数据

问题描述

我正在做一个个人项目,通过创建一个 DVD 库存应用程序来学习使用 SQLite3 和 Python。我在与 SQLite 相关的函数方面取得了一些成功,这些函数位于库文件中,旨在从应用程序的其他部分调用。

我遇到了在查询中返回无关数据的问题,在这种情况下,相同的数据两次。

我正在测试一个简单地查询表并返回其所有值的函数。如果我从它所在的库文件中的调用运行该函数,它可以正常工作,但如果我从导入库文件的外部文件调用它,它会返回两次数据,我不确定为什么。

功能如下:

def query_all():
con = db_connect()
cur = con.cursor()
cur.execute('''SELECT film_id, film_name, film_genre, date_added FROM 
film_inv''')
all_rows = cur.fetchall()
for row in all_rows:
    print('{0} : {1}, {2}, {3}'.format(row[0], row[1], row[2], row[3]))
con.close()

从库文件中运行时,它会返回正确的结果:

1 : Star Wars, Comedy, 2018-11-15 12:23:28
2 : Titanic, Drama, 2018-11-15 12:28:55
3 : Cars, Family, 2018-11-15 12:29:18
4 : Christmas Vacation, Holiday, 2018-11-15 12:37:59
6 : Cinderella, Family, 2018-11-15 12:43:13

Process finished with exit code 0

通过外部文件调用时,它会返回两次结果:

try:
    pydvd_utils.query_all()
except Exception as e:
    print(e)

1 : Star Wars, Comedy, 2018-11-15 12:23:28
2 : Titanic, Drama, 2018-11-15 12:28:55
3 : Cars, Family, 2018-11-15 12:29:18
4 : Christmas Vacation, Holiday, 2018-11-15 12:37:59
6 : Cinderella, Family, 2018-11-15 12:43:13
1 : Star Wars, Comedy, 2018-11-15 12:23:28
2 : Titanic, Drama, 2018-11-15 12:28:55
3 : Cars, Family, 2018-11-15 12:29:18
4 : Christmas Vacation, Holiday, 2018-11-15 12:37:59
6 : Cinderella, Family, 2018-11-15 12:43:13

Process finished with exit code 0

外部文件 query_all.py 很简单,只调用函数:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import pydvd_utils

try:
    pydvd_utils.query_all()
except Exception as e:
    print(e)

标签: pythonpython-3.xsqlite

解决方案


面对掌心时刻!

由于 PEBKAC 错误,该函数肯定运行了两次。

我调用了用于在库中直接测试的函数,但没有被注释掉。从外部调用函数是运行函数,然后是对库文件中存在的函数的调用。

注释掉对库中函数的测试调用解决了这个问题。

谢谢大家的指导。


推荐阅读