Home >Backend Development >Python Tutorial >How to Connect to a MySQL Database Using Python?

How to Connect to a MySQL Database Using Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-10 12:04:12282browse

How to Connect to a MySQL Database Using Python?

How to Connect to MySQL Using Python

Connecting to a MySQL database using a Python program involves the following steps:

1. Install MySQL Driver

Unlike PHP, Python does not install a MySQL driver by default. You will need to install MySQLdb or a similar driver package. For Python 2, MySQLdb is commonly used.

2. Establish Connection

Once the driver is installed, you can import it and establish a connection to your MySQL database. Here is an example code snippet:

import MySQLdb

db = MySQLdb.connect(host="localhost",
                     user="username",
                     passwd="password",
                     db="database_name")

3. Create a Cursor

After connecting to the database, you need to create a cursor object that will allow you to execute SQL queries.

cur = db.cursor()

4. Execute SQL Queries

You can now execute any SQL query using the cursor object. For example, to retrieve data from a table:

cur.execute("SELECT * FROM table_name")

5. Fetch and Print Results

The query results can be fetched and printed using a loop:

for row in cur.fetchall():
    print(row)

6. Close Connection

Once you are finished working with the database, remember to close the connection to free up resources.

db.close()

Advanced Usage

For more advanced usage, you can utilize Object Relational Mapping (ORM) tools like SQLAlchemy or peewee to simplify your interactions with the database. These tools allow you to manipulate data using Python objects instead of writing SQL queries manually.

The above is the detailed content of How to Connect to a MySQL Database Using Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn