Python MySQL – Connect

Python can work with a MySQL database using a driver (a library). In this series we use the official mysql-connector-python driver. We will use the same example as in our PHP MySQL chapters: a database named student with a table users.


What you need

  • MySQL server running on your computer (XAMPP, WAMP or MySQL installer).
  • Python 3 installed.
  • The MySQL driver for Python.

Install the driver with pip.

pip install mysql-connector-python

Create a database

First connect to the MySQL server without a database name. Then create the database.

import mysql.connector

conn = mysql.connector.connect(
    host="localhost",
    user="root",
    password=""
)
cursor = conn.cursor()

cursor.execute("CREATE DATABASE IF NOT EXISTS student")
print("Database student is ready")

conn.close()
Output of the above program is

Database student is ready

Note: The user root with an empty password is the default of XAMPP on a local computer only. On a real server always use a separate user with a strong password.

Connect to the database

Now add the database name in connect(). This is the connection code that we will use again in the next chapters.

import mysql.connector

conn = mysql.connector.connect(
    host="localhost",
    user="root",
    password="",
    database="student"
)

if conn.is_connected():
    print("Connected to MySQL")

conn.close()
Output of the above program is

Connected to MySQL

Always close the connection with conn.close() when your work is done.


Handle connection errors

A connection can fail if the server is off or the password is wrong. Wrap the code in try and except (see Python Errors) so the program does not crash.

import mysql.connector

try:
    conn = mysql.connector.connect(
        host="localhost",
        user="root",
        password="wrong",
        database="student"
    )
    print("Connected to MySQL")
    conn.close()
except mysql.connector.Error as err:
    print("Error:", err)
Output of the above program is

Error: 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

The exact error text depends on your MySQL version and the problem.


Summary

  • Install the driver with pip install mysql-connector-python.
  • Use mysql.connector.connect() with host, user, password and database.
  • Use conn.cursor() to run SQL, and conn.close() at the end.
  • Catch mysql.connector.Error to handle failures.
  • Next: create a table.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.