App overview screenshotSQL and Database Guides
Try our free SQL Client
Connecting to MySQL
Connecting to Drivers
Installing MySQL
Setting up MySQL
MySQL   >   
Connecting to Drivers   >   
MySQL with Python

Learn How To Connect MySQL with Python

If you’re working on a Python project, you often need a database to store information. MySQL is one of the most popular database systems available today. In this guide, we’ll walk you through how to connect your MySQL database with Python.

What You’ll Need

Installing MySQL Connector

In order to write Python scripts that can interact with a MySQL database, you’ll need to install and import a MySQL adapter. There are multiple options, but the most popular MySQL driver for Python is called MySQL Connector. Activate the virtual environment for your project and use pip to install:

pip install mysql-connector-python

Connecting to Your MySQL Database Using MySQL Connector

You’ll need to have your MySQL credentials. You can use this guide to find your credentials.

Once you have your credentials, import the MySQL connector driver and create a new connection using the connect() method:

import mysql.connector
connection = mysql.connector.connect(
    user = "myUser",
    password = "myPassword",
    host = "localhost",
    port = "3306",
    database = "myDB"

We can then open a cursor to start performing operations:


Querying Your Database

Once you have established your connection, you can query your MySQL database using Python. To create and run a query, use cursor.execute() like this:

cursor.execute(“SELECT ‘Arctype Archive: Your #1 Database Resource’ as message”);

You can also pass variables to cursor.execute() for both text and values parameters like this:

text = “INSERT INTO Users(username, email) VALUES(%s, %s) RETURNING *” 
values = (“Arctype”,”[](”)
cursor.execute(text, values)

You can get your results using the fetchall() method:

results = cursor.fetchall()

Using an SQL Client with MySQL and Python

Now that you’ve connected MySQL to your Python project, you often need to add or edit data. We recommend using an SQL client to do so. Check out our guide for setting up MySQL with Arctype in this tutorial.

Get help on databases and SQL. Join our Discord community.