怎么使用Python访问MySql数据库?
时间: 2024-12-13 11:25:57 浏览: 6
在Python中,你可以使用`pymysql`库或者更现代的`mysql-connector-python`库来连接和操作MySQL数据库。以下是基本步骤:
1. **安装所需库**:
- 安装`pymysql`:`pip install pymysql`
或者安装`mysql-connector-python`:`pip install mysql-connector-python`
2. **导入库并建立连接**:
```python
import pymysql
# 使用pymysql
connection = pymysql.connect(host='localhost', user='your_username', password='your_password', db='your_database')
# 使用mysql-connector-python (推荐)
from mysql.connector import connect
connection = connect(user='your_username', password='your_password', host='localhost', database='your_database')
```
替换上述代码中的`your_username`、`your_password`和`your_database`为你实际的数据库用户名、密码和数据库名。
3. **创建游标对象**:
```python
cursor = connection.cursor()
```
4. **执行SQL查询**:
```python
query = "SELECT * FROM your_table"
cursor.execute(query)
results = cursor.fetchall() # 获取所有结果
```
5. **处理结果**:
```python
for row in results:
print(row)
# 关闭游标和连接
cursor.close()
connection.close()
```
6. **异常处理**:
```python
try:
# ... 执行操作 ...
except Exception as e:
print(f"An error occurred: {e}")
finally:
# 确保关闭资源
if 'connection' in locals():
connection.close()
```
阅读全文