Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

MySQL Python Connection and Usage

MySQL Python Connection and Usage

MySQL is one of the most popular open-source relational databases, and Python is one of today's most popular programming languages. Combining Python with MySQL allows us to easily develop database-driven applications.

This article will introduce in detail how to connect to and operate MySQL databases using Python, covering the following:

  1. How to install the MySQL Python driver
  2. Establish and close database connections
  3. Execute various SQL queries
  4. Transaction management and error handling
  5. Best practices for database operations

Preparation

Install necessary software

Before you begin, please make sure you have installed the following software:

Install MySQL Connector/Python

You can install the official MySQL Python driver via pip:



pip install mysql-connector-python

Or install PyMySQL (another popular MySQL Python driver):



pip install pymysql


Connect to MySQL database

Establish a basic connection

The following is how to use mysql-connector-python Basic code for establishing a database connection:

Example

import

mysql.

connector

Creating a Database Connection

db

=

mysql.

connector

.

connect

(

    host

=

"localhost"

,

   

user

=

"yourusername"

,

    password

=

"yourpassword"

,

    database

=

"yourdatabase"

)

print

(

"Database connection successful!"

)

Connection parameter descriptions

Connect using PyMySQL

If you choose to use PyMySQL, the connection method is slightly different:

Example

import

pymysql

Creating a Database Connection

db

=

pymysql.

connect

(

    host

=

"localhost"

,

   

user

=

"yourusername"

,

    password

=

"yourpassword"

,

    database

=

"yourdatabase"

)

print

(

"Database connection successful!"

)


Executes an SQL query

Create a cursor object

Before executing SQL statements, we need to create a cursor object:

Example

cursor

=

db.

cursor

(

)

Execute a SELECT query

Example

cursor.

execute

(

"SELECT * FROM your_table"

)

Fetch all results

results

=

cursor.

fetchall

(

)

for

row

in

results:

   

print

(

row

)

Execute INSERT, UPDATE, DELETE operations

Example

Insert data

sql

=

"INSERT INTO users (name, age) VALUES (%s, %s)"

values

=

(

"Zhang San"

,

25

)

cursor.

execute

(

sql

,

values

)

Commit a transaction

db.

commit

(

)

print

(

cursor.

rowcount

,

" records inserted successfully"

)

Use parameterized queries

To prevent SQL injection, you should always use parameterized queries:

Example

sql

=

"SELECT * FROM users WHERE name = %s"

name

=

(

"Zhang San"

,

)

cursor.

execute

(

sql

,

name

)


Transaction management

Basic concepts of transactions

A MySQL transaction is a set of atomic SQL queries that either all execute successfully or none execute.

Using transactions

Example

try

:

   

Start a transaction

    cursor.

execute

(

"START TRANSACTION"

)

   

   

Execute multiple SQL statements

    cursor.

execute

(

"UPDATE accounts SET balance = balance - 100 WHERE id = 1"

)

    cursor.

execute

(

"UPDATE accounts SET balance = balance + 100 WHERE id = 2"

)

   

   

Commit a transaction

    db.

commit

(

)

   

print

(

"Transaction executed successfully"

)

except

Exception

as

e:

   

If an error occurs, roll back the transaction

    db.

rollback

(

)

   

print

(

"Transaction failed:"

,

e

)


Error handling

Catch database errors

Example

try

:

    cursor.

execute

(

"SELECT * FROM non_existent_table"

)

except

mysql.

connector

.

Error

as

err:

   

print

(

"Database error:"

,

err

)

Common error codes


Close the Connection

Close the connection properly

After completing database operations, you should close the cursor and connection:

Example

cursor.

close

(

)

db.

close

(

)

print

(

"Database connection closed"

)

Using the with statement

Python's with statement can automatically manage resources:

Example

with

mysql.

connector

.

connect

(

    host

=

"localhost"

,

   

user

=

"yourusername"

,

    password

=

"yourpassword"

,

    database

=

"yourdatabase"

)

as

db:

   

with

db.

cursor

(

)

as

cursor:

        cursor.

execute

(

"SELECT * FROM users"

)

        results

=

cursor.

fetchall

(

)

       

for

row

in

results:

           

print

(

row

)

The connection is automatically closed after leaving the with block


Best Practices

Connection pool

For applications that frequently connect to the database, it is recommended to use a connection pool:

Example

from

mysql.

connector

import

pooling

Create a connection pool

db_pool

=

pooling.

MySQLConnectionPool

(

    pool_name

=

"mypool"

,

    pool_size

=

5

,

    host

=

"localhost"

,

   

user

=

"yourusername"

,

    password

=

"yourpassword"

,

    database

=

"yourdatabase"

)

Get a connection from the connection pool

db

=

db_pool.

get_connection

(

)

ORM framework

For complex applications, you can consider using an ORM (Object-Relational Mapping) framework such as SQLAlchemy or Django ORM.