It is very easy to connect a MySQL database with a Python application, you can do this with the help of the MySQL connector package and execute your SQL queries right along with the Python application on Windows or ubuntu.
How to Connect to a MySQL Database in Python
Steps to connect to your MySQL database in Python and use SQL queries to get/retrieve, insert/store, delete/remove, and manipulate data on windows or ubuntu:
Step 1: Install the MySQL Connector in Python
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
To import the MySQL Connector package in the python app; Simply use import mysql.connector
for that:
import mysql.connector
Step 3: Connect the Python App to the Database
To connect your Python app to MySQL database on windows or ubuntu, 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)
Conclusion
That’s it! In this tutorial, you have learned how to connect mysql database in python apps.