python - 创建数据库时需要使用 commit() 吗?我把它放在哪里?
问题描述
import sqlite3
import random
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl
from urllib.request import urlopen
from collections import Counter
import re
conn = sqlite3.connect('EdwardH.sqlite')
cur = conn.cursor()
cur.execute('DROP TABLE IF EXISTS datasources')
cur.execute('DROP TABLE IF EXISTS StopWords')
cur.execute('DROP TABLE IF EXISTS IMDB')
cur.execute('DROP TABLE IF EXISTS NYT')
cur.execute('CREATE TABLE datasources (id INTEGER PRIMARY KEY ,
datasources INTEGER, description INTEGER, sourceurl WEBSITE )')
cur.execute('CREATE TABLE StopWords(id INTEGER, Word INTEGER, Freq INTEGER)')
cur.execute('CREATE TABLE IMDB(id INTEGER, Word INTEGER, Freq INTEGER )')
cur.execute('CREATE TABLE NYT(id INTEGER, Word INTEGER, Freq INTEGER )')
a1 = 0
a2 = 0
c1 = 0
count = {}
fhand1 = urllib.request.urlopen('https://raw.githubusercontent.com/nimdvir/teaching/master/stopwords.txt')
对于 fhand1 中的行: print(line.decode().strip())
for w in fhand1.read().strip().split():
c1 += 1
w = w.lower();
if w in count:
count[w] += 1
else:
count[w] = 1
for w, freq in count.items():
cur.execute('INSERT INTO StopWords (id, Word, Freq ) VALUES(?,?,?)',
(c1, w,count))
print(c1)
c2 = 0
count = {}
fhand2 = urllib.request.urlopen('https://raw.githubusercontent.com/nimdvir/teaching/master/imdb.txt')
for line in fhand2:
print(line.decode().strip())
for w in fhand2.read().split():
w = w.lower();
if w in count:
count[w] += 1
else:
count[w] = 1
for word, freq in count.items():
cur.execute('INSERT INTO IMDB (id, Word, Freq ) VALUES(?, ?,?)'
(c2,w,count))
count={}
fhand3 = urllib.request.urlopen('https://raw.githubusercontent.com/nimdvir/teaching/master/nyt.txt')
for line in fhand3:
print(line.decode().strip())
for w in fhand3.read().split():
w = w.lower();
if w in count:
count[w] += 1
else:
count[w] = 1
for word, freq in count.items():
cur.execute('INSERT INTO StopWords ( Word, Freq ) VALUES(?,?)',(w,count))
我想通过 StopWords、IMDB 和 NYT 运行数据库,但仍然没有结果。我对 db.commit() 进行了研究,但我不知道该把它放在哪里。编辑:我添加了完整的代码,这样你就可以看到整个事情并可能找到问题。
解决方案
是的,您需要它,默认情况下,pythonconn.cursor()
不会自动提交您的更改。commit
在所有更改后放置,您希望已执行,以保证全部或全部行为
只需将其放在最后一个插入循环之后(不在循环中),然后检查您的 sqlite
推荐阅读
- python - 如何在 UpdateView 中包含删除功能而不是 DeleteView
- arrays - 仅使用一个 if 语句的 Sumproduct 数组
- mongodb - 从 MongoDB Compass 执行命令
- javascript - 如何在 multiscroll.js div 下创建部分?
- c - 编译 Hello World 时未找到“stdio.h”文件
- sql - T-SQL 返回单个值而不是累积值
- bioinformatics - dyld:Mac OS High Sierra 中未加载库
- google-apps-script - 记录在 Google 电子表格中修改行的用户?
- c++ - 如何在 C++ 中通过 Clion 和 Cmake 使用 .so 库?
- firebase - 更新到最新库后无法检索 Firebase InstanceId 令牌