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 ?