In this post, we will see how we can connect MySQL in our python program in a a Windows Environment.

This example was created with Python 3.5

Here are the steps:

  1. Download and install Python-MySQL connector
  2. Create a database named python_db
  3. Create a table named employees with fields: id, name, gender
  4. Put some data in the table
  5. Here is the Python code to read data from the table:
    import mysql.connector
    from mysql.connector import errorcode
        # connect to database 
        cnx = mysql.connector.connect(user='root', password='', database='test')
        cursor = cnx.cursor()
        query = "select id,name,gender from employees"
        # execute the query  
        # read all the fields from cursor into variables
        for (id,name,gender) in cursor:
            print(id, "-" , name, "-" , gender)
    except mysql.connector.Error as err:
      if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Something is wrong with your user name or password")
      elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("Database does not exist")

That’s it.