python连接数据库生成折线图
时间: 2023-07-12 16:24:42 浏览: 52
首先,需要安装Matplotlib和pymysql模块。然后,可以按照以下步骤进行:
1. 连接数据库
```python
import pymysql
conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='database_name')
cursor = conn.cursor()
```
2. 执行SQL语句并获取数据
```python
sql = "SELECT * FROM table_name"
cursor.execute(sql)
data = cursor.fetchall()
```
3. 处理数据
```python
x = []
y = []
for row in data:
x.append(row[0])
y.append(row[1])
```
4. 绘制折线图
```python
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.xlabel('x轴')
plt.ylabel('y轴')
plt.title('折线图')
plt.show()
```
完整代码如下:
```python
import pymysql
import matplotlib.pyplot as plt
conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='database_name')
cursor = conn.cursor()
sql = "SELECT * FROM table_name"
cursor.execute(sql)
data = cursor.fetchall()
x = []
y = []
for row in data:
x.append(row[0])
y.append(row[1])
plt.plot(x, y)
plt.xlabel('x轴')
plt.ylabel('y轴')
plt.title('折线图')
plt.show()
```