I have a basic website, that execute multiple selects from a MSSQL. No one uses the website (just a website for me to test my knowledge). My challenge is that after a while, I have this error:
pyodbc.OperationalError: ('08S01', '[08S01] [Microsoft][ODBC Driver 18 for SQL Server]TCP Provider: Error code 0x68 (104) (SQLExecDirectW)')
I already did a internet search. Came across a few suggestions, including this one: Handle TCP Provider: Error code 0x68 (104) On this article, it's an intermittent error. Mine looks like a closed connection after a period of time. If I restart the Azure Web App and keep doing refresh during the day, I don't face the issue. It's only after a few hours of inactivity.
I tried a reconnect without success. This is my code
odbc_str = f'DRIVER={driver};SERVER={server};DATABASE={database};UID={username};PWD={password};Encrypt=yes;TrustServerCertificate=no;autocommit=True'
connection = pyodbc.connect(odbc_str, readonly=True)
cursor_conn = connection.cursor()
def get_results(seasonID):
global connection, cursor_conn, odbc_str # Usage of global variables is not best practice
if not connection: # Because the website does not have lots of traffic, I suspect the connection is drop
connection = pyodbc.connect(odbc_str, readonly=True)
cursor_conn = connection.cursor()
resultsQuery = "SELECT * FROM season_view"
return cursor_conn.execute(resultsQuery).fetchall()
Any suggestion?
Changed my code to open close a connection every time a query is made. Double checked and the errors were gone.
def get_results(seasonID):
global odbc_str
connection = pyodbc.connect(odbc_str, readonly=True)
cursor_conn = connection.cursor()
resultsQuery = "SELECT * FROM season_view"
execute_qry = cursor_conn.execute(resultsQuery).fetchall()
cursor_conn.close()
connection.close()
return execute_qry