Python MySQL Connection


MySQL Connection from Python

In this tutorial, we will learn how to install libraries required for a connection from Python to MySQL database, and how to make a connection.

Install mysql connector for python

To install MySQL connector for python using pip, run the following command.

pip install mysql-connector-python

Now, let us check if we can import mysql.connector in a Python program.

Run the following statement in a Python shell, or write the statement in a file and run the program. If there are no errors, then the installation of MySQL connector for Python is successful.

Python Program

import mysql.connector

Connection to MySQL from Python

Make sure that the MySQL database is running.

Now, run the following program, in which we connect to a MySQL instance running at localhost (our computer) with root user and corresponding password.

Python Program

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password="admin1234"
)

print(mydb)

Output

<mysql.connector.connection_cext.CMySQLConnection object at 0x1049e3f40>

Summary

In this tutorial of Python Examples, we learned how to make a connect to MySQL database instance from a Python program.