pymysql怎样执行sql文件
时间: 2023-10-23 10:32:59 浏览: 340
pymssql-2.2.4-cp37-cp37m-win_amd64.zip
要pymysql执行sql文件,可以按照以下步骤进行操作:
1. 首先,导入pymysql库并建立与数据库的连接:
```python
import pymysql
conn = pymysql.connect(host="127.0.0.1", user="root", password="", db="ceshi_install")
```
2. 创建游标对象:
```python
cursor = conn.cursor()
```
3. 打开并读取sql文件:
```python
with open('xc_ghavu_com.sql', 'r', encoding='utf-8') as f:
sql_statements = f.read()
```
4. 使用split(';')函数将sql文件中的语句分割成一个个单独的sql语句:
```python
sql_list = sql_statements.split(';')
```
5. 遍历sql_list,执行每个sql语句:
```python
for sql in sql_list:
try:
cursor.execute(sql)
conn.commit()
except Exception as e:
conn.rollback()
print("执行失败:", e)
```
6. 关闭游标和连接:
```python
cursor.close()
conn.close()
```
这样,你就可以使用pymysql来执行sql文件了。请注意,这个方法会将sql文件中的每个语句都执行一遍,因此在执行之前请确保你已经备份了数据库数据,以避免意外的数据损失。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [利用Python如何批量修改数据库执行Sql文件](https://download.csdn.net/download/weixin_38665814/13776371)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [Python连接mysql执行批量sql文件](https://blog.csdn.net/weixin_42230396/article/details/109735359)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [python 利用pymysql 直接导入sql文件,生成数据库](https://blog.csdn.net/qq_36400043/article/details/124264649)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
阅读全文