skip to Main Content
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


  1. Make sure to install the package mysql-connector-python because that’s where the mysql.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.

    pip install mysql-connector-python

    Login or Signup to reply.
  2. First do pip install mysql-connector-python.

    Now pass your data accordingly into the mydb method and try the code below:

    import mysql.connector
    
    mydb = mysql.connector.connect(
      host="localhost",
      user="root",
      password="",
      database="mysql"
    )
    
    mycursor = mydb.cursor()
    
    mycursor.execute("SELECT * FROM db")
    
    myresult = mycursor.fetchall()
    
    for x in myresult:
      print(x)
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search