如何在Python中运行SQL Server(MSSQL)的.sql文件?
在Python中运行SQL Server的.sql文件
可以通过pyodbc库连接SQL Server并执行.sql脚本文件,以下是针对你的场景的可行方案:
问题分析
你提供的代码在执行包含多语句的SQL脚本时可能失败,核心原因有两点:
pyodbc的cursor.execute()默认不支持一次性执行多条SQL语句- 执行DDL语句(如创建、删除表)后需要提交事务才能生效
修正后的可运行代码
import pyodbc import tempfile import os server_name = "localhost" db_name = "abc" password = "1234" local_path = tempfile.gettempdir() sqlfile = "test.sql" filepath = os.path.join(local_path, sqlfile) # 构建连接字符串(使用f-string提升可读性) connection_string = ( f'Driver={{ODBC Driver 17 for SQL Server}};' f'Server={server_name};' f'Database={db_name};' f'UID=sa;' f'PWD={password};' ) # 连接数据库并执行脚本 with pyodbc.connect(connection_string, autocommit=True) as cnxn: with cnxn.cursor() as cursor: with open(filepath, 'r', encoding='utf-8') as sql_file: sql_script = sql_file.read() # 拆分SQL语句并逐个执行 for statement in sql_script.split(';'): statement = statement.strip() if statement: cursor.execute(statement)
关键优化点
- 自动提交事务:通过
autocommit=True参数,让DDL语句执行后自动生效,无需手动调用cnxn.commit() - 拆分多语句:将脚本按分号拆分为单个语句执行,避免
execute()无法处理多语句的限制 - 编码指定:打开文件时添加
encoding='utf-8',防止特殊字符或中文读取异常
你的测试SQL脚本(test.sql)
IF EXISTS (SELECT * FROM sys.tables WHERE name = 'area' AND type = 'U') DROP TABLE area; CREATE TABLE area ( areaid int NOT NULL default '0', mapid int NOT NULL default '0', areaname varchar(50) default NULL, x1 int NOT NULL default '0', y1 int NOT NULL default '0', x2 int NOT NULL default '0', y2 int NOT NULL default '0', flag int NOT NULL default '0', restart int NOT NULL default '0', PRIMARY KEY (areaid) )
内容的提问来源于stack exchange,提问作者microset
相关产品推荐
相关产品推荐

