How to Connect to a MySQL Database in Python

How to Connect to a MySQL Database in Python

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.

Recommended Tutorials

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *