MySQL Forums
Forum List  »  Connector/Python

Mysql throwing an error but not able to catch using except
Posted by: vishva ZZ
Date: June 25, 2018 10:10PM

I was going through the docs for mysql connector and came across this.

https://dev.mysql.com/doc/connector-python/en/connector-python-example-ddl.html

This is a sample code which I am running. from future import print_function

import mysql.connector
from mysql.connector import errorcode

config = {
'user' : 'root',
'password' : 'root',
'host' : '127.0.0.1',
'raise_on_warnings' : True,
}
DB_NAME = 'testdbwhichdoesnotexist'
def createdatabase(cursor):
try:
cursor.execute('create database {} default character set "utf8"'.format(DB_NAME))
except mysql.connector.Error as err:
print('Failed creating database: {}'.format(err))
exit(1)

cnx = mysql.connector.connect(**config)
cursor = cnx.cursor()

try:
cnx.database = DB_NAME
except mysql.connector.Error as err:
if err.errno == errorcode.ER_BAD_DB_ERROR:
createdatabase(cursor)
cnx.database = DB_NAME
else:
print(err)
exit(1)
but if I assign DB_NAME to something new. It is throwing a error, but it is not being handled by the except which should create that respective db.

The error I see is :

Traceback (most recent call last):
File "msq.py", line 52, in <module>
cnx.database = DB_NAME
File "/home/*****/.local/lib/python3.5/site-packages/mysql/connector/connection_cext.py",line 138, in database
self._cmysql.select_db(value)
_mysql_connector.MySQLInterfaceError: Unknown database 'testdbwhichdoesnotexist'
Where am I going wrong ? Why is the exception not being handled by the except block ?

Options: ReplyQuote


Subject
Written By
Posted
Mysql throwing an error but not able to catch using except
June 25, 2018 10:10PM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.