简体   繁体   中英

How can i fix ValueError: parameters are of unsupported type in sqllite

I have Value Error in sql. I have Value Error in sql. I have insert command for insert to score to database but it doesn't change always be NULL.Actually, hashedScore = self.score but im.execute command doesn't work. Thanks for advices.

File "D:\SoftwareLabCodes\AboutPython\project5 deneme\main.py", line 272, in scoreSave im.execute("INSERT INTO userss5 (scores) VALUES (?)", (hashedScore)) ValueError: parameters are of unsupported type

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()

I believe this is one of those oddities where the documentation for placeholders in sqlite3 specify a tuple for your parameter values. BUT when you have a single item in a tuple like (hashedScore) python just reads that as an integer.

As an example:

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

5
(5, 10)

sqlite3 is needing a tuple and it only sees an integer, and throws the error.

Instead toss square brackets around that so it's read as a list, which is less ambiguous and works just fine for parameterization in sqlite3.

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

You could also use named parameters:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM