首页 > 解决方案 > 创建数据库时需要使用 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() 进行了研究,但我不知道该把它放在哪里。编辑:我添加了完整的代码,这样你就可以看到整个事情并可能找到问题。

标签: pythonsqlite

解决方案


是的,您需要它,默认情况下,pythonconn.cursor()不会自动提交您的更改。commit在所有更改后放置,您希望已执行,以保证全部或全部行为

只需将其放在最后一个插入循环之后(不在循环中),然后检查您的 sqlite


推荐阅读