python - 带有 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)
解决方案
面对掌心时刻!
由于 PEBKAC 错误,该函数肯定运行了两次。
我调用了用于在库中直接测试的函数,但没有被注释掉。从外部调用函数是运行函数,然后是对库文件中存在的函数的调用。
注释掉对库中函数的测试调用解决了这个问题。
谢谢大家的指导。
推荐阅读
- bash - ZFS 创建大括号扩展,如 mkdir -p
- html - CSS-样式“句柄”在没有 CSS 绝对的 div 之上
- binary-tree - 如何在不使用任何额外内存的情况下计算二叉树中的节点
- django - django-elasticsearch-dsl 与 AWS elasticsearch
- r - 在 ggplo2 上创建带有 2 个变量的条形图
- c - 哪种方法更适合在 c 中的两个进程之间进行对话?
- python - 如何通过多处理模块创建的工作进程在python中组合动态生成的测试套件
- laravel - 如何使表单中的动态字段得到验证和要求?
- nlp - spaCy:使用依赖解析在句子中查找根词的问题
- swift - Swift Realm 备份和恢复领域数据