python脚本导入sql文件
时间: 2025-03-13 07:01:16 浏览: 40
### 使用Python脚本执行导入SQL文件的操作
为了实现通过Python脚本来执行SQL文件中的命令,可以采用读取SQL文件内容并将其作为字符串传递给数据库连接对象来完成。下面是一个具体的例子说明如何利用`mysql.connector`库来进行这一过程[^1]。
#### 准备工作
确保已经安装了必要的包,可以通过pip工具安装所需的库:
```bash
pip install mysql-connector-python
```
#### Python代码示例
创建一个名为`execute_sql_file.py`的Python脚本:
```python
import mysql.connector
from pathlib import Path
def execute_sql_from_file(filename, host='localhost', user='', password='', database=''):
"""
执行来自指定路径下的SQL文件内的语句。
参数:
filename : str - SQL 文件的位置.
host : str - 数据库服务器地址,默认为本地主机.
user : str - 登录用户名.
password : str - 用户密码.
database : str - 要使用的数据库名称.
返回值:
None 或者 错误信息.
"""
try:
# 建立到MySQL数据库的连接
connection = mysql.connector.connect(
host=host,
user=user,
passwd=password,
db=database)
cursor = connection.cursor()
with open(Path(filename), 'r') as sql_file:
queries = sql_file.read().split(';')
for query in filter(None, map(str.strip, queries)):
cursor.execute(query + ';')
connection.commit()
print(f"成功执行 {filename}")
except Exception as e:
return f"发生错误: {e}"
finally:
if(connection.is_connected()):
cursor.close()
connection.close()
if __name__ == '__main__':
result = execute_sql_from_file('path/to/your/sqlfile.sql',
host='example_host',
user='example_user',
password='example_password',
database='example_db')
if isinstance(result, str): # 如果返回的是字符串,则表示有异常情况
print(result)
```
此段代码定义了一个函数`execute_sql_from_file()`用于接收SQL文件名以及其他必要参数(如主机、用户等),它会打开该文件并将其中的内容逐条发送至目标数据库执行。注意这里假设每一条完整的SQL指令是以分号结尾,并且会在分割后去除空白字符再逐一提交给游标去运行。
阅读全文
相关推荐


















