pymysql.connect 通讯加密_Python通过SSL加密连接MySQL
时间: 2023-08-10 20:04:07 浏览: 224
要通过SSL加密连接MySQL,需要在连接MySQL时使用SSL参数。具体步骤如下:
1. 安装PyMySQL模块
```python
pip install pymysql
```
2. 导入PyMySQL模块和ssl模块
```python
import pymysql
import ssl
```
3. 创建SSL上下文
```python
ssl_ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
ssl_ctx.load_cert_chain(certfile='server-cert.pem', keyfile='server-key.pem')
```
其中,'server-cert.pem'和'server-key.pem'分别是MySQL服务器的证书和私钥路径。
4. 连接MySQL并指定SSL参数
```python
conn = pymysql.connect(
host='localhost',
port=3306,
user='root',
password='password',
db='test',
ssl=ssl_ctx
)
```
其中,ssl参数指定SSL上下文。
5. 执行SQL语句
```python
with conn.cursor() as cursor:
cursor.execute('SELECT * FROM users')
result = cursor.fetchall()
print(result)
```
完整代码示例:
```python
import pymysql
import ssl
ssl_ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
ssl_ctx.load_cert_chain(certfile='server-cert.pem', keyfile='server-key.pem')
conn = pymysql.connect(
host='localhost',
port=3306,
user='root',
password='password',
db='test',
ssl=ssl_ctx
)
with conn.cursor() as cursor:
cursor.execute('SELECT * FROM users')
result = cursor.fetchall()
print(result)
conn.close()
```
注意:在MySQL服务器上启用SSL连接需要在my.cnf文件中配置。具体可参考MySQL官方文档。
阅读全文