Question

from tkinter import *
import tkinter as tk
import pyodbc

root1 = tk.Tk()

label1 = tk.Label(root1, text='product A')
input1 = StringVar()
entry1 = tk.Entry(root1,textvariable=input1)

label1.pack(side = tk.TOP)
entry1.pack()


buttonstr = tk.StringVar()
db = r"C:\Users\Goutham\Documents\keshav\testdb.accdb"




def odbc():
 '''
 connects with odbc
 '''        

 constr = 'Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=' + db
 conn = pyodbc.connect(constr, autocommit=True)
 cur = conn.cursor()
 check=input1.get()
 strsql = "select * from student where SName=%s"%(check)
 cur.execute(strsql)
 results = cur.fetchall()


 print (results,check)
 conn.close()


 buttonA = tk.Button(text = "hello", command = odbc)

 buttonA.pack()

I need this code to get input,store it in the variable -'check' and compare it with the values in the database using a SQL query.The matching values from the database are then displayed.

There seems to be a problem in the implementation of the SQL query.'check' stores the value of the input. The SQL query does not work properly and causes errors.

Please help.

Thank you.

Was it helpful?

Solution

You need to single quote the parameter to the WHERE clause:

strsql = "select * from student where SName='%s'" % (check,)

But be careful with building clauses like this (using string formatting), you run the risk of SQL injection. You should pass parameters instead:

strsql = "select * from student where SName=?"
cur.execute(strsql, (check,))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top