python怎样读取mysql中的数据
时间: 2024-01-12 11:05:41 浏览: 85
使用Python操作MySQL数据库需要先安装mysql-connector-python模块,然后按照以下步骤读取MySQL中的数据:
1. 导入mysql-connector-python模块:
```
import mysql.connector
```
2. 连接MySQL数据库:
```
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
```
3. 创建游标对象:
```
mycursor = mydb.cursor()
```
4. 执行SQL查询语句:
```
mycursor.execute("SELECT * FROM customers")
```
5. 获取查询结果:
```
myresult = mycursor.fetchall()
```
6. 遍历结果集:
```
for x in myresult:
print(x)
```
完整的读取MySQL数据的代码示例:
```
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
```
阅读全文