sqlite 如何修复ValueError:参数的类型在SQLLite中不受支持

6pp0gazn  于 2022-11-15  发布在  SQLite
关注(0)|答案(1)|浏览(182)

我在SQL中有值错误。我在SQL中有值错误。我使用INSERT命令将INSERT计分到数据库,但它不变,始终为NULL。实际上,hashedScore=self.core,但im.ecute命令不起作用。谢谢你的建议。
文件“D:\SoftwareLabCodes\AboutPython\Project5 deneme\main.py”,第272行,Score Save im.ecute(“Insert Into Userss5(Score)Values(?)”,(HashedScore))ValueError:参数的类型不受支持

import sqlite3 as sql
from tkinter import *
import hashlib
import tkinter as tk
from random import randint
from PIL import Image, ImageTk
import random


db = sql.connect("usersDataBase")
im = db.cursor()


def exit():
   window.destroy()

window = Tk()
window.title("Game Launcher")
window.geometry("900x900")
window.resizable(False,False)
title = Label(text = "Login Screen", font=('helvetica'))
title.place(relx=.4, rely=.15)

t ='CREATE TABLE IF NOT EXISTS userss5 (username VARCHAR (32), password VARCHAR(32), scores VARCHAR(32), userID INTEGER PRIMARY KEY AUTOINCREMENT )'
im.execute(t)
db.commit()


def insertToDb(username, password):

    hashedUsername = username.encode("UTF-8")
    hashedPassword = hashlib.md5(password.encode("UTF-8")).hexdigest()

    im.execute("INSERT INTO userss5 (username, password ) VALUES (?,?)",(hashedUsername,hashedPassword))
    db.commit()
    resultStr.set("Account created.")

def newAccountPage():
    global resultStr
    title.destroy()
    title2 = Label(text="Register Screen", font=('helvetica'))
    title2.place(relx=.4, rely=.15)

    newUser = Frame(window)
    newUser.place(relwidth=0.9, relheight=0.9,relx=0., rely=0.3)

    usernameLabel = Label(newUser, text="Username :", font=('helvetica'))
    usernameEntry = Entry(newUser, width=30, font=('helvetica'))
    usernameLabel.place(relx=.25, rely=.05)
    usernameEntry.place(relx=.42, rely=.05)

    passwordLabel = Label(newUser, text="Password :", font=('helvetica'))
    passwordEntry = Entry(newUser, width=30, show="*", font=('helvetica'))
    passwordLabel.place(relx=.25, rely=.15)
    passwordEntry.place(relx=.42, rely=.15)


    resultStr = StringVar()
    result = Label(newUser, textvariable=resultStr,font=('helvetica'))
    result.place(relx= .45, rely=.7)

    register = Button(newUser, text="Register", bg="green", fg="white",font=('helvetica'),command=lambda: insertToDb(usernameEntry.get(), passwordEntry.get()))
    register.place(relx=.42, rely=.25)

    exitButton = Button(newUser, text="Exit", bg="red", command=exit, font=('helvetica'))
    exitButton.place(relx=.60, rely=.45)

    back = Button(newUser, text="Back", bg="red", fg="white", command=lambda:[newUser.place_forget(),title2.destroy()],font=('helvetica'))
    back.place(relx=.84,rely=.25)

def auth(username, password):
    resultLogin = StringVar()
    resultLabel = Label(homePage, textvariable= resultLogin)
    resultLabel.place(relx=.45,rely=.7)
    im.execute("SELECT COUNT (*) FROM userss5")
    count = im.fetchall()
    if count[0][0] == 0:
        resultLogin.set("User not found")
        return
    else:
        matchUser = False
        matchPassword = False
        userID = 0
        hashedPassword = hashlib.md5(password.encode("UTF-8")).hexdigest()
        hashedUsername = username.encode("UTF-8")
        im.execute("SELECT * FROM userss5 WHERE username = ?",(hashedUsername,))
        query = im.fetchone()
        try:
            length = len(query)
        except:
            length= 0
        if length > 0:
            matchUser = True
            idnum = query[2]
            if query[1] == hashedPassword:
                matchPassword = True
                resultLogin.set("Login successful")
                loginOther(idnum)
            else:
                resultLogin.set("Wrong password or username.")
        else:
            resultLogin.set("Wrong password or username.")

def loginOther(userID):


    homePage.place_forget()
    userID = Frame(window)
    menu = Menu(userID)
    madde = Menu(menu, tearoff= False)
    snakeGameButton = Button(userID, text="Snake Game", bg="green",command=lambda :[snakeGame(),snakeGameButton.destroy(),ticTacToeGameButton.destroy(),userInfoLabel.destroy()],font=('helvetica'))
    snakeGameButton.place(relx=.12, rely=.25)
    ticTacToeGameButton = Button(userID, text="Tic Tac Toe", bg="blue", command=lambda:[ticTacToe(),snakeGameButton.destroy(),ticTacToeGameButton.destroy(),userInfoLabel.destroy()],font=('helvetica'))
    ticTacToeGameButton.place(relx=.70, rely=.25)
    userID.place(relwidth=.9,relheight=.9,relx=.05,rely=.03)
    userInfoLabel = Label(userID, text="Welcome to launcher.Please choose game",font=('helvetica'))
    userInfoLabel.place(relx=.25, rely=.1)
    exitButton = Button(userID, text="Exit", bg="red", command=exit, font=('helvetica', 20)).place(x=350, y=700)

def snakeGame():



    MOVE_INCREMENT = 20
    MOVES_PER_SECOND = 15
    GAME_SPEED = 1500 // MOVES_PER_SECOND

    class Snake(tk.Canvas):
        def __init__(self):
            super().__init__(
                width=600, height=620, background="black", highlightthickness=0
            )

            self.snake_positions = [(100, 100), (80, 100), (60, 100)]
            self.food_position = self.set_new_food_position()
            self.direction = "Right"

            self.score = 0

            self.load_assets()
            self.create_objects()

            self.bind_all("<Key>", self.on_key_press)

            self.pack()

            self.after(GAME_SPEED, self.perform_actions)

        def load_assets(self):
            try:
                self.snake_body_image = Image.open("./assets/snake.png")
                self.snake_body = ImageTk.PhotoImage(self.snake_body_image)

                self.food_image = Image.open("./assets/food.png")
                self.food = ImageTk.PhotoImage(self.food_image)
            except IOError as error:
                window.destroy()
                raise

        def create_objects(self):
            self.create_text(35, 12, text=f"Score: {self.score}", tag="score", fill="#fff", font=10)
            self.create_text(530,12, text=f"Last Score: ", fill="#fff", font=10 )

            for x_position, y_position in self.snake_positions:
                self.create_image(
                    x_position, y_position, image=self.snake_body, tag="snake"
                )

            self.create_image(*self.food_position, image=self.food, tag="food")
            self.create_rectangle(7, 27, 593, 613, outline="#525d69")

        def check_collisions(self):
            head_x_position, head_y_position = self.snake_positions[0]

            return (
                    head_x_position in (0, 600)
                    or head_y_position in (20, 620)
                    or (head_x_position, head_y_position) in self.snake_positions[1:]
            )

        def check_food_collision(self):
            if self.snake_positions[0] == self.food_position:
                self.score += 1
                self.snake_positions.append(self.snake_positions[-1])

                self.create_image(
                    *self.snake_positions[-1], image=self.snake_body, tag="snake"
                )
                self.food_position = self.set_new_food_position()
                self.coords(self.find_withtag("food"), *self.food_position)

                score = self.find_withtag("score")
                self.itemconfigure(score, text=f"Score: {self.score}", tag="score")

        def end_game(self):

            self.delete(tk.ALL)
            self.create_text(
                self.winfo_width() / 2,
                self.winfo_height() / 2,
                text=f"Game over! You scored {self.score}!",
                fill="#fff",
                font=14
            )
            self.scoreSave()



        def move_snake(self):
            head_x_position, head_y_position = self.snake_positions[0]

            if self.direction == "Left":
                new_head_position = (head_x_position - MOVE_INCREMENT, head_y_position)
            elif self.direction == "Right":
                new_head_position = (head_x_position + MOVE_INCREMENT, head_y_position)
            elif self.direction == "Down":
                new_head_position = (head_x_position, head_y_position + MOVE_INCREMENT)
            elif self.direction == "Up":
                new_head_position = (head_x_position, head_y_position - MOVE_INCREMENT)

            self.snake_positions = [new_head_position] + self.snake_positions[:-1]

            for segment, position in zip(self.find_withtag("snake"), self.snake_positions):
                self.coords(segment, position)

        def on_key_press(self, e):
            new_direction = e.keysym

            all_directions = ("Up", "Down", "Left", "Right")
            opposites = ({"Up", "Down"}, {"Left", "Right"})

            if (
                    new_direction in all_directions
                    and {new_direction, self.direction} not in opposites
            ):
                self.direction = new_direction

        def perform_actions(self):
            if self.check_collisions():
                self.end_game()

            self.check_food_collision()
            self.move_snake()

            self.after(GAME_SPEED, self.perform_actions)

        def set_new_food_position(self):
            while True:
                x_position = randint(1, 29) * MOVE_INCREMENT
                y_position = randint(3, 30) * MOVE_INCREMENT
                food_position = (x_position, y_position)

                if food_position not in self.snake_positions:
                    return food_position

        def scoreSave(self):

            hashedScore = self.score
            im.execute("INSERT INTO userss5 (scores) VALUES (?)", (hashedScore))



    frame = Frame(window)
    frame.pack()
    board = Snake()


homePage = Frame(window)
homePage.place(relwidth=0.9, relheight=0.9,relx=0., rely=0.3)

usernameLabel = Label(homePage, text="Username :", font=('helvetica'))
usernameEntry = Entry(homePage, width= 30, font=('helvetica'))
usernameLabel.place(relx=.25 , rely=.05 )
usernameEntry.place(relx=.42 , rely=.05 )

passwordLabel = Label(homePage, text="Password :" ,font=('helvetica'))
passwordEntry = Entry(homePage, width= 30,show="*",font=('helvetica'))
passwordLabel.place(relx=.25 , rely=.15)
passwordEntry.place(relx=.42 , rely=.15)

login = Button(homePage, text= "Login", fg="blue", font=('helvetica'),command=lambda: auth(usernameEntry.get(),passwordEntry.get()))
login.place(relx=.46, rely=.25)

register = Button(homePage, text= "Register", fg="green", command=newAccountPage, font=('helvetica'))
register.place(relx=.45, rely=.35)

exitButton = Button(homePage, text="Exit", bg="red", command=exit, font=('helvetica'))
exitButton.place(relx=.45, rely=.45)


window.mainloop()
puruo6ea

puruo6ea1#

我认为这是一件奇怪的事情,在SQLITE3中的占位符文档中为您的参数值指定了一个元组。但是,当您在像(hashedScore)这样的元组中有单个项时,python只是将其读取为一个整数。
举个例子:

print((5))
print((5,10))

5
(5, 10)

sqlite3需要一个元组,并且它只看到一个整数,并抛出错误。
取而代之的是去掉方括号,这样它就会被读作一个列表,这样就不会有太多歧义,而且对于SQLite3中的参数化来说也很好用。

im.execute("INSERT INTO userss5 (scores) VALUES (?)", [hashedScore])

您还可以使用命名参数:

im.execute("INSERT INTO userss5 (scores) VALUES (:score)", {'score':hashedScore})

相关问题