Handle Named Query Timeout in Python

I have a script for comparing the current value of a tag to the last value stored in the DB for that tag, and then storing the current value. Of course, this means I have to run a query to read the last value. The call looks like this:

lastDBvalue = system.db.runNamedQuery("Project", "Read_DB", {"tag_name" : PlcTag})

This query works, and calling it works, but how do I handle the situation where this is the first entry in the table for the tag? When the query times out, what is the value of lastDBvalue?

Currently, this is how I have it written, but it doesn't seem to be working for the last 3 tags that I added.

#get latest DB info
lastDBvalue = system.db.runNamedQuery("Project", "Read_DB", {"tag_name" : PlcTag})
if ( not ((0 == lastDBvalue.rowCount))):
	lastVal = lastDBvalue.getValueAt(0,'val')
	lastTime = lastDBvalue.getValueAt(0,'t_stamp')
	deltaT = system.date.secondsBetween(lastTime,system.date.now())
		
#large enough change in value to log the change, or minSample time is met
if ((0 == lastDBvalue.rowCount) or (abs(currentValue - lastVal) >= historicalDeadband) or ((minSampleRate > 0) and (deltaT >= minSampleRate))):
	system.db.runNamedQuery("Project", "Store_Tag_Change", {"tag_name":PlcTag,"val":currentValue})

I might need to add a Try: Except:, but haven't used that much so not sure where to put the Except:

Or maybe I need to edit my query:

SELECT TOP 1 val, t_stamp FROM Data where tag_id=:tag_name order by t_stamp desc

Trying to add IF EXISTS before the select, I get SQLServerException: A result set was generated for update.

IF EXISTS (select 1 from Data Where tag_id = :tag_name)
	SELECT TOP 1 val, t_stamp FROM Data where tag_id=:tag_name order by t_stamp desc

The reason for the error was I was running it in the database query browser. Running it with system.db.runQuery(), I was able to get a result set.

Looks like it'll be a combination of both. Adding the IF EXISTS prevents the query from timing out and using try: except: handles the error thrown when the query does not return a result set.


Query:

IF EXISTS (SELECT 1 FROM Data where tag_id=:tag_name)
	SELECT TOP 1 val, t_stamp FROM Data where tag_id=:tag_name order by t_stamp desc

Script:
#get latest DB info
noEntries = 0
try:
	lastDBvalue = system.db.runNamedQuery("Project", "Read_DB",{"tag_name" : PlcTag})
	if ( not ((0 == lastDBvalue.rowCount))):
		lastVal = lastDBvalue.getValueAt(0,'val')
		lastTime = lastDBvalue.getValueAt(0,'t_stamp')
		deltaT = system.date.secondsBetween(lastTime,system.date.now())
except:
	noEntries = 1
			
		
#large enough change in value to log the change
if (((0 == lastDBvalue.rowCount) or (1 == noEntries)) or (abs(currentValue - lastVal) >= historicalDeadband) or ((minSampleRate > 0) and (deltaT >= minSampleRate))):
	system.db.runNamedQuery("Project", "Store_Tag_Change", {"tag_name":PlcTag,"val":currentValue})