sqlite 无法插入值

tquggr8v  于 2022-11-24  发布在  SQLite
关注(0)|答案(1)|浏览(282)

我创建了一个表,但无法插入值。Database类:

import sqlite3

class Database:    
    word_list = ["RAFAY", "LION", "PANDA", "TIGER", "DOG", "CAT", "RABBIT", "MOUSE", "PENGUIN"]

    def __init__(self, db):
        self.con = sqlite3.connect(db)
        self.cur = self.con.cursor()
        self.cur.execute("CREATE TABLE IF NOT EXISTS DICTIONARY (ID INTEGER PRIMARY KEY, WORD TEXT NOT NULL)")
        self.con.commit()

    def add_valid_guessing_word(self):
        for word in self.word_list:
            self.insert_valid_guessing_word(word)

    # Insert Function
    def insert_valid_guessing_word(self, guessing_word):
        cursor = self.con.cursor()
        cursor.execute("INSERT INTO DICTIONARY VALUES (NULL,?)", (guessing_word,))
        print("Inserted Data")
        self.con.commit()

    # Get a Record in DB
    def get_valid_guessing_word(self, id):
        cursor = self.con.cursor()
        cursor.execute("SELECT * FROM DICTIONARY WHERE id=?", (id,))
        valid_word = self.cur.fetchone()
        print(valid_word)
        return valid_word

主要代码:

from tkinter import *
from tkinter import messagebox
from string import ascii_uppercase
import random
import sqlite3
from sqdb import Database

window = Tk()
window.title("Hangman")
db = Database("Goiyala.db")

photos = [PhotoImage(file="images/hang0.png"), PhotoImage(file="images/hang1.png"), PhotoImage(file="images/hang2.png"),
          PhotoImage(file="images/hang3.png"),
          PhotoImage(file="images/hang4.png"), PhotoImage(file="images/hang5.png"), PhotoImage(file="images/hang6.png"),
          PhotoImage(file="images/hang7.png"),
          PhotoImage(file="images/hang8.png"), PhotoImage(file="images/hang9.png"),
          PhotoImage(file="images/hang10.png"), PhotoImage(file="images/hang11.png")]

def newGame():
    messagebox.showinfo("Welcome to Hangman","By Roman & Ricario")
    global the_word_withSpaces
    global numberOfGuesses
    global the_word
    numberOfGuesses = 0
    imgLabel.config(image=photos[0])
    value = db.get_valid_guessing_word(random.randint(1, 7))
    the_word = str(value[-1])
    print(the_word)
    the_word_withSpaces = " ".join(the_word)
    lblWord.set(" ".join("_" * len(the_word)))

def guess(letter):
    global numberOfGuesses
    if numberOfGuesses < 11:
        txt = list(the_word_withSpaces)
        guessed = list(lblWord.get())
        if the_word_withSpaces.count(letter) > 0:
            for c in range(len(txt)):
                if txt[c] == letter:
                    guessed[c] = letter
                lblWord.set("".join(guessed))
                if lblWord.get() == the_word_withSpaces:
                    messagebox.showinfo("Hangman", "You Guessed it")
                    newGame()
        else:
            numberOfGuesses += 1
            imgLabel.config(image=photos[numberOfGuesses])
            if numberOfGuesses == 11:
                toast_message = "Game Over! " \
                                "The Correct answer is {}".format(the_word)
                messagebox.showwarning("Hangman", toast_message)

imgLabel = Label(window)
imgLabel.grid(row=0, column=0, columnspan=3, padx=10, pady=40)
imgLabel.config(image=photos[0])

lblWord = StringVar()
Label(window, textvariable=lblWord, font="Consolas 24 bold").grid(row=0, column=3, columnspan=6, padx=10)
n = 0
for c in ascii_uppercase:
    Button(window, text=c, command=lambda c=c: guess(c), font="Helvetica 18", width=4).grid(row=1 + n // 9, column=n % 9)
    n += 1

Button(window, text="new\nGame", command=lambda: newGame(), font="Helvetica 10 bold").grid(row=3, column=8,
                                                                                           sticky="NSWE")

newGame()
window.mainloop()

错误:

Traceback (most recent call last):
  File "C:\Users\Rufez\PycharmProjects\HangmanRicarioRoman2\game.py", line 128, in <module>
    hangman = Game(touch.get_valid_word_to_be_execute())
  File "C:\Users\Rufez\PycharmProjects\HangmanRicarioRoman2\game.py", line 41, in get_valid_word_to_be_execute
    the_word = str(value[-1])
TypeError: 'NoneType' object is not subscriptable
vpfxa7rd

vpfxa7rd1#

您不能重复使用光标。
每次声明一个本地游标:

# Get a Record in DB
def get_valid_guessing_word(self, id):
    cursor = self.con.cursor()                                     # <<-- HERE new cursor
    cursor.execute("SELECT * FROM DICTIONARY WHERE id=?", (id,))
    valid_word = cursor.fetchone()
    print(valid_word)
    return valid_word

正如@kuro在多个注解中指出的,代码中从来没有调用过Database.add_valid_guessing_word()函数,所以表是空的,所以对db.get_valid_guessing_word(random.randint(1, 7))的调用返回None,这不是列表类型,因此出现了错误。
修改代码,将Animals放入数据库:

window.title("Hangman")
db = Database("Goiyala.db")
db.add_valid_guessing_word()   # <<-- HERE Populate the database

但这会不断地添加单词,所以也许先检查一下它是否是空的,比如:

window.title("Hangman")
db = Database("Goiyala.db")
if ( db.get_valid_guessing_word( 0 ) == None ):
    db.add_valid_guessing_word()   # <<-- HERE Populate IFF empty

然后,您还可以执行数据库的调试转储:

class Database:

    # ...

    def dumpAnimals( self ):
       """ Debug function to dump the Animal Dictionary Table """
        cursor = self.con.cursor()
        cursor.execute( "SELECT id, word FROM Dictionary ORDER BY word" )
        for row in cursor.fetchall():
            if ( row == None ):
                print( "Dictionary Table is empty" )
                break
            else:
                id_num, word = row
                print( "id=%3d, word=[%s]" % ( id_num, word ) )

使用如下方式:

window.title("Hangman")
db = Database("Goiyala.db")
if ( db.get_valid_guessing_word( 0 ) == None ):
    db.add_valid_guessing_word()   # <<-- HERE Populate IFF empty
db.dumpAnimals()                   # <<-- HERE Check we have data

相关问题