Python: Connect to MySQL

- 3 mins

Overview

  1. Install MySQL Connector/Python using pip.
  2. Establish MySQL database Connection from Python.
  3. Define the SELECT statement query. Here you need to know the table, and it’s column details.
  4. Execute the SELECT query using the cursor.execute() method.
  5. Get resultSet from the cursor object using a cursor.fetchall(),cursor.fetchmany() or cursor.fetchone().
  6. Ierate over the ResultSet and get each row and its column value.
  7. Catch any SQL exceptions that may come up during the process.
  8. Close the Python database connection.

Example

# 1. Install MySQL Connector/Python using pip.
pip install --allow-external mysql-connector-python
import datetime
import mysql.connector
from mysql.connector import Error

try:
# 2. Establish MySQL database Connection from Python.
    connection = mysql.connector.connect(host='localhost',
                                         database='employees',
                                         user='user',
                                         password='password')

# 3. Define the SELECT statement query.
    query = ("SELECT first_name, last_name, hire_date FROM employees "
             "WHERE hire_date BETWEEN %s AND %s")

# 4. Execute the SELECT query using the cursor.execute() method.
    cursor = connection.cursor()

    hire_start = datetime.date(1999, 1, 1)
    hire_end = datetime.date(1999, 12, 31)

    cursor.execute(query, (hire_start, hire_end))

# 5. Get resultSet from the cursor object.
    records = cursor.fetchall()

# 6. Ierate over the ResultSet and get each row and its column value.
    print("Total number of rows in employees is: ", cursor.rowcount)

    print("\n1. Printing each employee record:\n")
    for (first_name, last_name, hire_date) in records[:3]:
        print("{}, {} was hired on {:%d-%b-%Y}".format(
            last_name, first_name, hire_date))

    print("\n2. Printing each employee card:\n")
    for row in records[:2]:
        print("first name = ", row[0])
        print("last name = ", row[1])
        print("hire date  = ", row[2], "\n")

# 7. Catch any SQL exceptions that may come up during the process.
except Error as e:
    print("Error reading data from MySQL table:", e)

finally:
    if (connection.is_connected()):
        cursor.close()

# 8. Close the Python database connection.
        connection.close()
        print("MySQL connection is closed")


Install Employees database

1. Install the data folder from Github repo and follow the tutorial.
2. Change directory to the repository, then run mysql < employees.sql.

If you want to install with two large partitioned tables, run mysql < employees_partitioned.sql.

In bash, you execute a .sql script using mysql -u user -p < db.sql.
So here you run mysql -u user -p < employees.sql

3. After installing, you can run one of the following
mysql -t < test_employees_md5.sql
#or
mysql -t < test_employees_sha.sql

Reference

Zhijian Liu

Zhijian Liu

A foodaholic

comments powered by Disqus
rss facebook twitter github gitlab youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora quora