python和sqlite在违反唯一约束时插入失败

2024-05-08 16:05:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我要计算他们的大量文字。它太大了,无法在内存中保存字典,所以我使用sqlite来完成这个任务。我编写了一个数据库类,并使用这个词作为主键,因为它应该是唯一的。在

在这个过程中的某个地方它失败了,因为“频率”这个词试图被添加两次。我不知道为什么会发生这种事,因为还有很多其他的常用词,肯定已经数到两次了。。。这是我的两份文件。。。。在

在数据库管理员.py在

import sqlite3
import sys



class Database():
    '''Creates an object with method for adding and checking words against an sqlite database'''

def __init__(self):
    self.dbname = raw_input('What will be the name of this database: ')
    self.table1 = 'words'
    self.column1 = 'word_name'
    self.column1t = 'TEXT'
    self.column2 = 'frequency'
    self.column2t = 'INTEGER'
    self.conn = sqlite3.connect(self.dbname)
    self.c = self.conn.cursor()
    self.c.execute('CREATE TABLE {tn} ({nf} {ft} PRIMARY KEY)'.\
        format(tn=self.table1, nf=self.column1, ft=self.column1t))
    self.c.execute('ALTER TABLE {tn} ADD COLUMN {cn} {ct}'.\
        format(tn=self.table1, cn=self.column2, ct=self.column2t))
    self.conn.commit()
    self.checkfile = open('check.txt', 'w+')



def check_word(self, word_name):
    exist = self.c.execute('SELECT * FROM {tn} WHERE {cn}="{wn}"'.\
        format(tn=self.table1, cn=self.column1, wn=word_name))

    exist = self.c.fetchall()
    if exist:
        new_freq = exist[0][1] + 1
        self.c.execute("UPDATE {tn} SET {c2n}={en} WHERE {c1n}='{word}'".\
            format(tn=self.table1, c2n=self.column2, en=new_freq, c1n=self.column1, word=word_name))
        return True
    else:
        return False



def add_word(self, word_name, frequency=1):
    self.checkfile.write('%s\n' % word_name)
    self.c.execute('INSERT INTO {tn} ({c1n}, {c2n}) VALUES ("{wn}", {f})'.\
        format(tn=self.table1, c1n=self.column1, c2n=self.column2, wn=word_name, f=frequency))

在嘎吱声.py在

^{pr2}$

在数据库连接提交() 配电箱连接关闭()

这是我的错误:

Traceback (most recent call last):
  File "crunch.py", line 13, in <module>
    db.add_word(word)
  File "/home/ubuntu/wikicorpus/dbmaker.py", line 44, in add_word
    format(tn=self.table1, c1n=self.column1, c2n=self.column2, wn=word_name, f=frequency))

sqlite3.IntegrityError:唯一约束失败:words.word_名称在


Tags: namepyselfformatexecutecntnword

热门问题