import mysql.connector
cnx = mysql.connector.connect(
user='db',
password='yab@db',
host='3306',
database='database1'
)
cursor = cnx.cursor()
query = 'SELECT * FROM your_table'
cursor.execute(query)
results = cursor.fetchall()
for row in results:
print(row)
cursor.close()
cnx.close()
I am try to connect to mysql database through python but it showed error no module named mysql connector even though i install python_mysql_connector during the installation of mysql
2
Answers
Make sure to install the package
mysql-connector-python
because that’s where themysql.connector
Class comes from. Also if you’re using a virtual environment, you should try to install it within that rather than doing it globally.First do
pip install mysql-connector-python
.Now pass your data accordingly into the
mydb
method and try the code below:I tested it, it works fine for me.
If you still experience issues with this, it must be that something is wrong with your database connection or that python in your script doesn’t correspond to the right path. If that is the case, do this:
<full path to python> -m pip install mysql-connector-python
and try again.