python - Python 仅在 SQLite DB 上插入一行
问题描述
为什么我的代码只插入一行?
thewholeenchilada = ("SELECT SUBSTR(email, (SELECT INSTR(email,'@'))) AS org, SUM(count) as count FROM Em GROUP BY org ORDER BY count DESC")
for salida in cur.execute(thewholeenchilada):
cur.execute('''INSERT INTO Counts (org, count)
VALUES (?, ?)''', (salida[0],row[1]))
print((str(salida[0]), salida[1]))
conn.commit()
解决方案
避免循环并运行一个INSERT INTO ... SELECT
查询。现在,您在循环内外重复使用相同的光标会导致处理问题。要么使用两个不同的游标,要么有效地组合并让数据库引擎运行操作查询:
sql = '''INSERT INTO Counts (org, [count])
SELECT SUBSTR(email, INSTR(email, '@')+1) AS org,
SUM(count) as [count]
FROM Em
GROUP BY org
ORDER BY count DESC
'''
cur.execute(sql)
conn.commit()
推荐阅读
- python - Pyomo 中的非固定边界错误来解决 MILP
- rust - 为什么我不能在方法中混合返回和表达式
- database - mongodb一直在吸内存
- azure-logic-apps - 自定义连接器操作 webhook 错误处理
- c++ - 从其他线程锁定类成员
- javascript - 将目录内容作为对象添加到数组中
- sql - 我需要根据两个条件从查询中删除行
- python - 如何对字典python的每个键的值进行排序?
- sql-server - 使用过滤条件查找 tasktype(taskcount,bugcount) 的计数,
- sql - 对 SQL Server 中的长时间运行时间进行基本故障排除的建议