如何用python连接网页和mysql
时间: 2023-09-07 09:12:34 浏览: 54
连接网页:
1. 使用requests库发送HTTP请求获取网页内容:
```python
import requests
# 发送GET请求
response = requests.get("http://www.example.com")
# 获取响应内容
content = response.content
```
2. 使用urllib库发送HTTP请求获取网页内容:
```python
from urllib import request
# 发送GET请求
response = request.urlopen("http://www.example.com")
# 获取响应内容
content = response.read()
```
连接MySQL:
1. 使用pymysql库连接MySQL数据库:
```python
import pymysql
# 连接MySQL数据库
conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='test')
# 创建游标对象
cursor = conn.cursor()
# 执行SQL语句
cursor.execute("SELECT * FROM users")
# 获取查询结果
result = cursor.fetchall()
# 关闭游标和连接
cursor.close()
conn.close()
```
2. 使用MySQLdb库连接MySQL数据库:
```python
import MySQLdb
# 连接MySQL数据库
conn = MySQLdb.connect(host='localhost', port=3306, user='root', password='password', db='test')
# 创建游标对象
cursor = conn.cursor()
# 执行SQL语句
cursor.execute("SELECT * FROM users")
# 获取查询结果
result = cursor.fetchall()
# 关闭游标和连接
cursor.close()
conn.close()
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)