python操作mysql:连接
时间: 2024-10-25 16:06:25 浏览: 35
在Python中,我们可以使用多种库来连接MySQL数据库,其中最常用的是`pymysql`库。以下是基本的步骤:
1. 安装库:首先确保已经安装了`pip`,然后通过以下命令安装`pymysql`:
```
pip install pymysql
```
2. 连接数据库:
```python
import pymysql
# 创建连接参数
host = 'localhost'
user = 'your_username'
password = 'your_password'
database = 'your_database'
# 连接到MySQL服务器
try:
conn = pymysql.connect(host=host,
user=user,
password=password,
db=database,
charset='utf8mb4', # 设置字符集,避免乱码
cursorclass=pymysql.cursors.DictCursor) # 使用字典游标返回结果
except pymysql.MySQLError as e:
print(f"Error connecting to MySQL: {e}")
else:
print("Connected to MySQL successfully.")
```
这里的`cursorclass`参数可以根据需要选择,`DictCursor`会将查询结果转化为字典形式。
阅读全文
相关推荐


















