user13950756
user13950756

Reputation:

how to grab a specific row from sql3 tables

Im trying to make a program so that the user can input a country, and the program can output the entire row of information using tkinter and sqlite 3. Here is my code so far, please let me know if you see any other holes in my code,and thank you in advance! :)

    from  tkinter import *
    bobert=Tk()
    bobert.geometry("600x600")
    import sqlite3
    
    connection = sqlite3.connect('covidproject.db')
    cursor = connection.cursor()
    
    country_name=StringVar()
    
    label1=Label(bobert,text="World Covid Stats",fg="black",font=("sand script",20))
    label1.place(x=183,y=100)
    
    label2=Label(bobert,text="Name of Country:",fg="black",font=("sand script",15))
    label2.place(x=130,y=150)
    
    n=Entry(bobert,textvariable=country_name)
    n.place(x=310,y=158)
    
    def subby():
        answer=country_name.get()
        cursor.execute("SELECT * FROM covid WHERE name LIKE '"+answer+"'")
        data=cursor.fetchall()
    
    submit=Button(bobert, text="SUBMIT", fg="black",font=("arial",13),command=subby)
    submit.place(x=260,y=200)
    
    bobert.mainloop

Upvotes: 0

Views: 95

Answers (3)

Delrius Euphoria
Delrius Euphoria

Reputation: 15098

The best way I would recommend is passing it as parameters like

def subby():
        answer=country_name.get()
        l_answer = answer.capitalize()
        sql_command = "SELECT * FROM covid WHERE `name` = ?;"
        values = (l_answer,)
        cursor.execute(sql_command,values)
        data = cursor.fetchall()

Since you are using = it should be noted that the string must be converted to exactly like the details in your table. So using answer.capitalize() will capitalize the first letter of your entry and search accordingly to it.

Alternatively, if you want to make code shorter you can avoid the parametric substitution here and also use recursive definition for the variable

def subby():
        answer=country_name.get()
        answer = answer.capitalize()
        cursor.execute("SELECT * FROM covid WHERE `name` = ?;",(answer,))
        data = cursor.fetchall()

Happy coding :D

Upvotes: 1

Laraib Sid
Laraib Sid

Reputation: 36

You can always use f-sting for formatting.

cursor.execute(f"SELECT * FROM covid WHERE name = {answer}")

Upvotes: 0

Salik Malik
Salik Malik

Reputation: 207

I assume that the variable answer contains the name of the country.
All you need to do is apply formatting

Instead of this

cursor.execute("SELECT * FROM covid WHERE name LIKE '"+answer+"'")

Try

cursor.execute("SELECT * FROM covid WHERE name = {}".format(answer))

Upvotes: 0

Related Questions