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.
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
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:
cursor=connection.cursor()
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”,”[test@arctype.com](mailto:test@arctype.com)”)
cursor.execute(text, values)
You can get your results using the fetchall()
method:
results = cursor.fetchall()
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.