Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I except specific kinds of pymysql.err.InternalErrors, not just all of them?

I am writing a function to that can add a new table to my database. The problem I am having is when the table already exist I get the error message:

pymysql.err.InternalError: (1050, "Table 'doesthiswork' already exists")

So I added an except to my code which works but it is excepting all Internal errors. How do I get my code to except the specific error which I am assuming is 1050 not Internal Errors in general?

import pymysql

def CreateTable(Host,User,Password,DataBase,TableName):

    try:
        conn = pymysql.connect(
                           host = Host,
                           user = User,
                           password= Password,
                           db = DataBase
                          )
        a = conn.cursor()
        tblName = TableName
        sql = 'CREATE TABLE'+" "+ tblName + '(try varchar(128));'

        a.execute(sql)

    except pymysql.err.InternalError: 
        print (tblName + " " + 'already exist')

The above code works, but as stated earlier if a different type of internal error surfaced it would just except that as table already exist not the actual error itself.

like image 368
ZacAttack Avatar asked Jan 08 '17 22:01

ZacAttack


2 Answers

Assign the exception to a variable and test the specific error codes, e.g.:

except pymysql.err.InternalError as e:
    code, msg = e.args
    if code == 1050:
        print(tblName, 'already exists')

Though you can probably just print(msg).

like image 65
AChampion Avatar answered Oct 02 '22 14:10

AChampion


You don't have to hardcode the code values, they are available in the pymysql.constants.ER module. And you can have a mapping between error codes and error messages, which can help to scale this approach to handling more errors without multiplying the if/else blocks:

from pymysql.constants import ER

error_codes = {
   ER.TABLE_EXISTS_ERROR: "Table already exists",
   ER.ACCESS_DENIED_ERROR: "Access denied"
}

try:
    # ...
except pymysql.err.InternalError as e:
    code, msg = e.args
    print(error_codes.get(code, msg))
like image 30
alecxe Avatar answered Oct 02 '22 13:10

alecxe