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.
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)
.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With