- Notifications
You must be signed in to change notification settings - Fork27
Exception
Jahnvi Thakkar edited this pageFeb 17, 2025 ·3 revisions
The mssql-python module defines a set of exceptions specified in thePython DB API to handle various database-related errors. Proper error handling is crucial for diagnosing issues and ensuring the robustness of your application.
Exception Classes
The module defines several custom exception classes that are inherited from Python's built-in Exception class. These classes represent different categories of database errors:
- Warning: Represents general warnings.
- OperationalError: Represents errors related to the database's operation.
- DataError: Represents errors related to the data being processed.
- IntegrityError: Represents errors related to data integrity constraints.
- ProgrammingError: Represents errors related to the database programming interface.
- NotSupportedError: Represents errors related to unsupported features.
Error Code Mapping
When an error occurs, the type of exception raised is determined by the SQLSTATE value provided by the database.
| SQLSTATE | Exception |
|---|---|
| 0A000 | mssql_python.NotSupportedError |
| 40002 | mssql_python.IntegrityError |
| 22*** | mssql_python.DataError |
| 23*** | mssql_python.IntegrityError |
| 24*** | mssql_python.ProgrammingError |
| 25*** | mssql_python.ProgrammingError |
| 42*** | mssql_python.ProgrammingError |
| HYT00 | mssql_python.OperationalError |
| HYT01 | mssql_python.OperationalError |
For instance, a primary key violation (attempting to insert a duplicate key) will raise an IntegrityError.
Here is an example demonstrating how to use the custom exceptions in the mssql-python module:
frommssql_pythonimportconnectfrommssql_python.exceptionsimportDatabaseError,InterfaceErrortry:# Establish a connectionconn=connect("Server=ServerAddress;Database=myDataBase;UID=myUsername;PWD=myPassword;")# Create a cursor objectcursor=conn.cursor()# Execute a querycursor.execute("SELECT * FROM Employees")# Fetch resultsrows=cursor.fetchall()forrowinrows:print(row)exceptDatabaseErrorase:print(f"Database error occurred:{e}")exceptInterfaceErrorase:print(f"Interface error occurred:{e}")finally:# Close the cursor and connectioncursor.close()conn.close()