If you are working in Python programming language. And you want to make your Python app dynamic. For this, you need to connect your Python app to a database. In this tutorial, you will learn how to connect your Python app to a MySQL database.
How to Connect to a MySQL Database in Python
By using these steps, you can connect to your MySQL database in Python and execute SQL queries to get/retrieve, insert/store, delete/remove, and manipulate data:
- Step 1: Install the MySQL Connector Package
- Step 2: Import the Connector Module
- Step 3: Connect Python App to the Database
- Step 4: Create a Cursor Object
- Step 5: Execute SQL Statements
- Step 6: Retrieve Data from the Database
Step 1: Install the MySQL Connector Package
Firstly, open your terminal or command prompt and execute the pip command into it to connect to install the MySQL Connector package, which is used to connect MySQL database in pyhton app:
pip install mysql-connector-python
Step 2: Import the Connector Module
Next, import the MySQL Connector package in the python app. You can do this using the following code:
Step 3: Connect Python App to the Database
After that, To connect your Python app to MySQL database, you’ll need to create a connection object. You can do this by the following code:
mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="mydatabase" )
Step 4: Create a Cursor Object
Once you’ve connected your Python app to the database, you need to create a cursor object.
mycursor = mydb.cursor()
Step 5: Execute SQL Statements
Using the cursor object, you can execute SQL statements in your python app.
For example, you can execute a SELECT statement to retrieve data from a table:
mycursor.execute("SELECT * FROM customers")
Step 6: Retrieve Data from the Database
Once you have executed the SQL statement using the above given command. And now, you can get or retrieve the data from the database using the fetch() method of the Cursor object. Here’s an example code:
myresult = mycursor.fetchall() for x in myresult: print(x)
That’s it! In this tutorial, you have learned how to connect mysql database in python apps.