Home > Net >  How to handle OperationalError/DatabaseError in sqlite3 Python
How to handle OperationalError/DatabaseError in sqlite3 Python

Time:10-28

Why can't I catch OperationalError/DatabaseError through try/except syntax in sqlite3 python?

I also imported these errors with "from sqlite3 import OperationalError".

The code I was running is:

import pandas as pd
import sqlite3
from sqlite3 import OperationalError
from sqlite3 import DatabaseError

con = sqlite3.connect(r'F:\ANALIS\FIXD_INC\PRODUCTS\FI_Daily\new_db\DB\main.db')

try:
    table = pd.read_sql("""SELECT * FROM giberish;""", con=con)
except (OperationalError, DatabaseError):
    table = None

Note the the database file (.db) can be any directory, but it DOESN"T contain table "giberish" in it. So it is expected that the error will occur. My goal is to learn to handle it properly.

The output is following:

OperationalError                          Traceback (most recent call last)
~\Anaconda3\lib\site-packages\pandas\io\sql.py in execute(self, *args, **kwargs)
   2019         try:
-> 2020             cur.execute(*args, **kwargs)
   2021             return cur

OperationalError: no such table: giberish

The above exception was the direct cause of the following exception:

DatabaseError                             Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_10372/402971868.py in <module>
      1 try:
----> 2     table = pd.read_sql("""SELECT * FROM giberish;""", con=con)
      3 except (OperationalError, DatabaseError):
      4     table = None

~\Anaconda3\lib\site-packages\pandas\io\sql.py in read_sql(sql, con, index_col, coerce_float, params, parse_dates, columns, chunksize)
    564 
    565     if isinstance(pandas_sql, SQLiteDatabase):
--> 566         return pandas_sql.read_query(
    567             sql,
    568             index_col=index_col,

~\Anaconda3\lib\site-packages\pandas\io\sql.py in read_query(self, sql, index_col, coerce_float, params, parse_dates, chunksize, dtype)
   2078 
   2079         args = _convert_params(sql, params)
-> 2080         cursor = self.execute(*args)
   2081         columns = [col_desc[0] for col_desc in cursor.description]
   2082 

~\Anaconda3\lib\site-packages\pandas\io\sql.py in execute(self, *args, **kwargs)
   2030 
   2031             ex = DatabaseError(f"Execution failed on sql '{args[0]}': {exc}")
-> 2032             raise ex from exc
   2033 
   2034     @staticmethod

DatabaseError: Execution failed on sql 'SELECT * FROM giberish;': no such table: giberish

Also meant to ask which one Error should I use the DatabaseError or OperationalError? I specified them both in the code to make sure the problem is not in the error name.

CodePudding user response:

You need to catch the pandas database error. When you make a pandas call, catch pandas errors. sqlite3 errors should be handled on direct sqlite3 calls. So, import DatabaseError from pandas, not sqlite3:

from pandas.io.sql import DatabaseError
  • Related