Python连接MySQL数据库的方法

Python连接MySQL数据库的方法

技术背景

在Python开发中,经常需要与数据库进行交互,MySQL是一种广泛使用的关系型数据库。Python提供了多种方式来连接MySQL数据库,不同的方法有不同的特点和适用场景。

实现步骤

1. 安装数据库驱动

在Python中连接MySQL,首先需要安装相应的驱动。常见的驱动有MySQLdbmysql-connector-pythonpymysql等。

  • MySQLdb:仅支持Python 2,在不同操作系统上安装方式不同。
    • Windows:可以下载MySQLdb的exe文件进行安装。
    • Linux:可以使用包管理器进行安装,如在Debian系系统中使用sudo apt-get install python-mysqldb
    • Mac:可以使用Macport进行安装。
  • mysql-connector-python:由MySQL官方提供,纯Python实现,系统独立,安装简单。可以使用pip install mysql-connector-python进行安装。
  • pymysql:纯Python实现,无外部依赖,安装过程在所有操作系统上一致且简单。使用pip install pymysql进行安装。

2. 建立数据库连接

mysql-connector-python为例,示例代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import mysql.connector

# 建立连接
mydb = mysql.connector.connect(
host="localhost",
user="username",
passwd="password",
database="database_name"
)

# 创建游标对象
mycursor = mydb.cursor()

# 执行SQL查询
mycursor.execute("SELECT * FROM your_table")

# 获取查询结果
results = mycursor.fetchall()
for row in results:
print(row)

# 关闭连接
mydb.close()

3. 使用ORM(可选)

为了避免手动编写SQL语句,可以使用ORM(对象关系映射)工具,如SQLAlchemypeewee

  • SQLAlchemy:是Python的SQL工具包和对象关系映射器,功能强大,适用于大型项目。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

# 创建引擎
engine = create_engine("mysql://user:password@host/db_name")

# 创建会话
Session = sessionmaker(bind=engine)
session = Session()

# 执行查询
result = session.execute("SELECT * FROM your_table")
for row in result:
print(row)

# 关闭会话
session.close()
  • peewee:轻量级ORM,简单易用,适合小型项目。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from peewee import *

# 连接数据库
db = MySQLDatabase('db_name', user='user', passwd='password')

# 定义模型类
class Book(Model):
author = CharField()
title = TextField()

class Meta:
database = db

# 创建表
Book.create_table()

# 插入数据
book = Book(author="me", title='Peewee is cool')
book.save()

# 查询数据
for book in Book.filter(author="me"):
print(book.title)

核心代码

以下是使用pymysql进行数据库操作的完整示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import pymysql.cursors

# 连接到数据库
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)

try:
with connection.cursor() as cursor:
# 创建新记录
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('[email protected]', 'very-secret'))

# 提交更改
connection.commit()

with connection.cursor() as cursor:
# 读取单条记录
sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
cursor.execute(sql, ('[email protected]',))
result = cursor.fetchone()
print(result)
finally:
# 关闭连接
connection.close()

最佳实践

  • 异常处理:在连接数据库和执行SQL语句时,应该进行异常处理,以确保程序的健壮性。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import mysql.connector
from mysql.connector import Error

try:
conn = mysql.connector.connect(host='hostname',
database='db',
user='root',
password='passcode')
if conn.is_connected():
cursor = conn.cursor()
cursor.execute("select database();")
record = cursor.fetchall()
print("You're connected to - ", record)
except Error as e:
print("Print your error msg", e)
finally:
# 关闭数据库连接
if conn.is_connected():
cursor.close()
conn.close()
  • 使用上下文管理器:对于支持上下文管理器的数据库驱动,如pymysql,可以使用with语句来管理数据库连接和游标,确保资源的正确释放。

常见问题

  • 驱动安装失败:可能是网络问题、依赖缺失等原因导致。可以检查网络连接,安装必要的依赖库,或者尝试使用镜像源进行安装。
  • 连接数据库失败:可能是数据库地址、用户名、密码、数据库名等信息错误,或者数据库服务未启动。可以检查这些信息是否正确,确保数据库服务正常运行。
  • SQL语句执行错误:可能是SQL语法错误、表名或字段名错误等原因导致。可以检查SQL语句的语法,确保表名和字段名正确。

Python连接MySQL数据库的方法
https://119291.xyz/posts/2025-04-22.python-connection-to-mysql-database/
作者
ww
发布于
2025年4月23日
许可协议