1. 使用 `mysql-connector-python` 库:
这是官方提供的MySQL连接器,支持Python 2和3版本。可以通过 `pip install mysql-connector-python` 命令安装。
示例代码:
import mysql.connector
# 建立连接
cnx = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# 创建游标对象
cursor = cnx.cursor()
# 执行SQL查询
query = "SELECT * FROM yourtable"
cursor.execute(query)
# 获取查询结果
result = cursor.fetchall()
# 遍历结果
for row in result:
print(row)
# 关闭游标和连接
cursor.close()
cnx.close()
2. 使用 `pymysql` 库:
`pymysql` 是一个纯Python编写的MySQL客户端库,用于连接MySQL数据库。可以通过 `pip install pymysql` 命令安装。
示例代码:
import pymysql
# 建立连接
cnx = pymysql.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# 创建游标对象
cursor = cnx.cursor()
# 执行SQL查询
query = "SELECT * FROM yourtable"
cursor.execute(query)
# 获取查询结果
result = cursor.fetchall()
# 遍历结果
for row in result:
print(row)
# 关闭游标和连接
cursor.close()
cnx.close()
3. 使用 `SQLAlchemy` 库:
`SQLAlchemy` 是一个Python SQL工具和对象关系映射(ORM)库,它提供了一种更高级的方式来连接和操作MySQL数据库。可以通过 `pip install sqlalchemy` 命令安装。
示例代码:
from sqlalchemy import create_engine
# 建立连接
engine = create_engine('mysql+pymysql://yourusername:yourpassword@localhost/yourdatabase')
# 执行SQL查询
query = "SELECT * FROM yourtable"
result = engine.execute(query)
# 遍历结果
for row in result:
print(row)
# 关闭连接
engine.dispose()
这些是连接MySQL数据库的几种常用方式,你可以根据自己的需求选择适合的方式进行连接和操作。
Python连接MySQL数据库的方式有多种,以下是其中几种常用的方式,每种方式都有详细的解释和示例代码:
猜你喜欢
转载自blog.csdn.net/weixin_49786960/article/details/131613648
今日推荐
周排行