'I am unable to catch the exception created when querying a non existent SAP HANA table using pyodbc/python
I want to create a new table if I query a table that ends up being non existent. I thought to do this via catching the exception generated, but I can unable to do that despite specifying the error that pops up in my except statement.
Each of the try blocks I have below lead the two exception at the end.
import pyodbc as py
qry = \
"""
SELECT *
FROM NON_EXISTENT_TABLE
"""
cmd = \
"""
CREATE TABLE SOME_TABLE(VAR1 VARCHAR(10),
VAR2 VARCHAR(50), VAR3 VARCHAR(5), VAR4 VARCHAR(6));
"""
try:
df = pd.read_sql_query(qry, py.connect('DSN=SOMEDSN; Trusted_Connection = Yes'))
except py.ProgrammingError:
py.connect('DSN=SOMEDSN; Trusted_Connection=Yes').cursor().execute(cmd)
try:
df = pd.read_sql_query(qry, py.connect('DSN=SOMEDSN; Trusted_Connection = Yes'))
except py.DatabaseError:
py.connect('DSN=SOMEDSN; Trusted_Connection=Yes').cursor().execute(cmd)
This is the error I get
ProgrammingError: ('42S02', '[42S02] [SAP AG][LIBODBCHDB DLL][HDBODBC] Base table or view not found;259 invalid table name: Could not find table/view NON_EXISTENT_TABLE in schema SOMESCHEMA: line 3 col 15 (at pos 25) (259) (SQLExecDirectW)')
The above exception was the direct cause of the following exception:
DatabaseError: Execution failed on sql '
SELECT *
FROM SOMESCHEMA.NON_EXISTENT_TABLE
': ('42S02', '[42S02] [SAP AG][LIBODBCHDB DLL][HDBODBC] Base table or view not found;259 invalid table name: Could not find table/view NON_EXISTENT_TABLE in schema SOMESCHEMA: line 3 col 15 (at pos 25) (259) (SQLExecDirectW)')
Solution 1:[1]
I am not able to provide an answer on the specific Python issue. However, it may be helpful for you to know, that SAP offers an advanced Python client for SAP HANA, which makes life a lot easier especially when working with Pandas dataframes.
With the hana-ml client, you can use function has_table to check if a table exists. Depending on the outcome you may use function create_table to create a new table. Finally you can use the HANA Dataframe to query data and collect the result as a Pandas dataframe.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mathias Kemeter |
