‘’’
This code was running with no issues and connecting to a remote mysql DB and not sure why it is failing now with this error. Appreciate any help as I am new to python.
The ERROR
Traceback (most recent call last):
File “C:/PROJECTS/Python/mySQL/mySQL_Forum.py”, line 2, in
from mysql.connector import Error
ImportError: cannot import name ‘Error’ from ‘mysql.connector’ (unknown location)
I have masked out my clients db credentials which are correct, the database server is running.
'''
import mysql.connector
from mysql.connector import Error
HOST = "*******************"
PORT = "****"
USER = "*******"
PASSWD = "*******"
DATABASE = "******"
try:
mydb = mysql.connector.connect(
host= HOST,
port=PORT,
user=USER,
passwd=PASSWD,
database=DATABASE
)
if mydb.is_connected():
print("Successfully connected to the database")
else:
print("Connection failed")
cursor = mydb.cursor()
cursor.execute("SELECT DATABASE();")
record = cursor.fetchone()
print("You're connected to database:", record[0])
# My code should go here
except Error as e:
print(f"Error: {e}")
finally:
if 'cursor' in locals():
cursor.close()
if 'mydb' in locals() and mydb.is_connected():
mydb.close()
print("MySQL connection is closed")
'''
Blockquote
Thankyou Matthew for your timely reply. I did implement the change and got the following
Traceback (most recent call last):
File “C:\PROJECTS\Python\mySQL\mySQL_BK.py”, line 2, in
from mysql.connector.errors import Error
ModuleNotFoundError: No module named ‘mysql.connector.errors’
Blockquote
The strange thing being this code worked and now it doesn’t. I am sure that it’s something I have done when I uninstalled the pip mysql-python-connector and reinstalled it again. But not experienced enough to understand what effect this would have had. If I comment out the mysql.connector.errors import Error then I get this error:
Blockquote
Exception has occurred: AttributeError
module ‘mysql.connector’ has no attribute ‘connect’
File “C:\PROJECTS\Python\mySQL\mySQL_BK.py”, line 15, in
mydb = mysql.connector.connect(
^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: module ‘mysql.connector’ has no attribute ‘connect’
I trapped the above error in debug mode in VS Code. Still scratching my head.
Hi Barry… I renamed the file but still getting the same failures. When I mask the 2nd line the failure jumps to line 5 mydb = mysql.connector.connect(…) and I get this error
Traceback (most recent call last):
File “C:\PROJECTS\Python\mySQL\cliffsql.py”, line 5, in
mydb = mysql.connector.connect(
AttributeError: module ‘mysql.connector’ has no attribute ‘connect’
Really appreciate the feedback and thank you for getting involved.
Matthew and Barry
I uninstalled the mysql-connector-python and reinstalled it then system restart and I can now connect once again to my remote mysql DB. Not sure why this worked, but it did. Thank you both again for your time and talents.