Python Forum
Error Handling/No results from SQL Query
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Error Handling/No results from SQL Query
#1
Hello - I have what I would think should be a fairly simple problem, but I just cannot get it to work. The app I'm building is pretty straightforward. User opens the app, enters a value (a problem ID, called PROBLEMID) and clicks a button. The app checks a SQL table for that value and returns back a user name.

I have gotten it to work when the problem ID is FOUND in the database table, but when the id doesn't exist, I just get an error. Can you help set me straight? I can't get TRY to work, or any IF not or IF !=

Thank you in advance for any help.

Here's the entirety of my code (and yes, I know it's lousy and inefficient)
import tkinter as tk #python3.x
from tkinter import messagebox
#import Tkinter as tk #python2.x
from tkinter import *
import pyodbc

#Set Up App Window & defaults
root = tk.Tk()
root.option_add("*Font", "Verdana")
root.configure(background='black')
root.geometry('220x125') # Size WxH
root.title("SERV OWNER FINDER")

#create labels and entry boxes
PROBIDLABEL = Label(root, text="Enter Problem ID ", bg = "Black", fg = "gray")
PROBIDENTRY = Entry(root, bg="light yellow")

PROBIDLABEL.place(x=1,y=3)
PROBIDENTRY.place(x=1,y=30)

def close_window(): 
    root.destroy()

def checktable():
        problemid = "'" + PROBIDENTRY.get() + "'"
        connstring = 'DRIVER={SQL Server};SERVER=OBDEVSQLAGL05;DATABASE=DCollection;UID=xxxx;PWD=yyyy'
        SQLstr="select OWNER from GD_SERV_ADMIN where PROBLEMID = " + problemid
        conn=pyodbc.connect(connstring)
        cursor=conn.cursor()
        cursor.execute(SQLstr)
        row = cursor.fetchone()
        messagebox.showinfo("Owner found", "The ADMIN for this problem ID is:  " + row[0])
        cursor.close()
        PROBIDENTRY.delete(0,END)
        
#Create Buttons
SubmitButton = Button(root, text="Submit", width = 8, command=checktable)
QuitButton = Button(root, text="Quit",width = 8, command=close_window)

#Place Buttons on Window
QuitButton.place(x=5, y=70)
SubmitButton.place(x=120, y=70)

root.mainloop()
Reply
#2
Please show example error code (unaltered, and complete).
It tells a lot about the reason, I suspect you need to enclose the code in a try, except clause.
The error traceback should show the specific error.
Reply
#3
Quote: but when the id doesn't exist, I just get an error
Check that row[0] has something in it, i.e. a length
row = cursor.fetchone()
msg="That ID is not found"
if len(row):
    msg="Owner found", "The ADMIN for this problem ID is:  " + row[0])
messagebox.showinfo(msg) 
Note that the SQL server you are using may return None or an error message when not found, so you would then print row to see which not found error condition you should test for.
Reply
#4
Thank you both for taking the time to have a look and assist!

Larz60+
The full error I'm currently getting back is
Exception in Tkinter callback
Error:
Traceback (most recent call last): File "C:\Program Files\Anaconda3\lib\tkinter\__init__.py", line 1549, in __call__ return self.func(*args) File "C:\Users\jromano1\AppData\Local\Programs\Python\Python36-32\Scripts\SERV_CHECK.py", line 32, in checktable messagebox.showinfo("Owner found", "The ADMIN for this problem ID is: " + row[0]) TypeError: 'NoneType' object is not subscriptable
WOOEE
I get this error
Exception in Tkinter callback
Error:
Traceback (most recent call last): File "C:\Program Files\Anaconda3\lib\tkinter\__init__.py", line 1549, in __call__ return self.func(*args) File "C:\Users\jromano1\AppData\Local\Programs\Python\Python36-32\Scripts\SERV_CHECK2.py", line 33, in checktable if len(row): TypeError: object of type 'NoneType' has no len()
Reply
#5
it should be
row = cursor.fetchone()
if row:
    messagebox.showinfo("Owner found", "The ADMIN for this problem ID is:  " + row[0])
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#6
buran
Thank you (for your response and for fixing my tags again).

I made the change you suggested and now when I run it, I don't get any response nor do I get any error messages. It just does this line
PROBIDENTRY.delete(0,END)

FYI, I did put that line in the python code tags but it's not showing up that way here now. No idea why

I found my error and it's now working as expected. Thank you all SO MUCH for your help!

row = cursor.fetchone()
        if row:
            messagebox.showinfo("Owner found", "The ADMIN for this problem ID is:  " + row[0])
            
        else:
            messagebox.showinfo("Owner Not Found", "This problem ID was not found in the database!")
        cursor.close()
        PROBIDENTRY.delete(0,END)
Reply
#7
obviously your SELECT statement does not return anything. And thus cursor.fetchone() returns None. As a result your previous code was raising an exception. Now it just continue.
try
def checktable():
        problemid = PROBIDENTRY.get()
        connstring = 'DRIVER={SQL Server};SERVER=OBDEVSQLAGL05;DATABASE=DCollection;UID=xxxx;PWD=yyyy'
        SQLstr="select OWNER from GD_SERV_ADMIN where PROBLEMID=?"
        conn=pyodbc.connect(connstring)
        cursor=conn.cursor()
        cursor.execute(SQLstr, problemid )
        row = cursor.fetchone()
        if row:
            messagebox.showinfo("Owner found", "The ADMIN for this problem ID is:  " + row[0])
        cursor.close()
        PROBIDENTRY.delete(0,END)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#8
Excellent, thank you!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Star python exception handling handling .... with traceback mg24 3 1,216 Nov-09-2022, 07:29 PM
Last Post: Gribouillis
  Help needed with a "for loop" + error handling tamiri 2 2,389 May-27-2022, 12:21 PM
Last Post: tamiri
  Mysql error message: Lost connection to MySQL server during query tomtom 6 15,677 Feb-09-2022, 09:55 AM
Last Post: ibreeden
  pymysql: insert query throws error wardancer84 12 4,419 Jan-28-2022, 06:48 AM
Last Post: wardancer84
  Query Syntax Error hammer 2 1,586 Jan-03-2022, 02:30 PM
Last Post: hammer
  Handling Python Fatal Error richajain1785 7 5,760 Oct-14-2021, 01:34 PM
Last Post: Tails86
  TypeError: sequence item 0: expected str instance, float found Error Query eddywinch82 1 5,026 Sep-04-2021, 09:16 PM
Last Post: eddywinch82
  Error using mariadb select query with form in python? shams 2 1,956 Jul-29-2021, 12:30 PM
Last Post: shams
  Error Handling JarredAwesome 5 2,842 Oct-17-2020, 12:41 AM
Last Post: JarredAwesome
  Compiling Python 3.8.5 source code results in build error Deepan 0 2,143 Sep-14-2020, 04:11 AM
Last Post: Deepan

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020