我正在尝试使用sqlalchemy在Python中使用红色并执行SQL文件。应该简单吧?
conn=sqlalchemy.create_engine('mssql+pyodbc://' + DSN).connect()
query = open('../toy_example.sql',encoding="utf-8").read()
trans = conn.begin()
conn.execute(query)
trans.commit()
我收到此错误
ProgrammingError: (pyodbc.ProgrammingError) ('42000', "[42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Incorrect syntax near '\ufeff'. (102) (SQLExecDirectW)")
[SQL: drop table temp;
With t0 as (select 1+1)
select * into temp from t0]
为什么会出现此错误?我不确定这是文件编码错误还是SQLAlchemy错误。理想情况下,这应该很简单。
编辑:
此代码在表临时存在的情况下正常工作:
conn=sqlalchemy.create_engine('mssql+pyodbc://' + DSN).connect()
query = "drop table temp; With t0 as (select 1+1 t) select * into temp from t0"
trans = conn.begin()
conn.execute(query)
trans.commit()
编辑2:
供参考,这里是文件toy_example.sql的链接。http://s000.tinyupload.com/index.php?file_id=62746453331292257227
((我在SQL Server Management Studio中将其保存为编码的UTF-8代码页65001)
SSMS“高级保存选项”对话框中“编码”列表顶部附近的UTF-8选项是“带签名的UTF-8”
该选项将在文件的开头写入Unicode BOM(字节顺序标记),编码为\xEF\xBB\xBF
如果我们使用标准的“ utf-8”编码在Python中读取文件,我们将获得字符串中包含的Unicode BOM字符\ufeff
with open(r"C:\Users\Gord\Desktop\SQLQuery1.sql", encoding="utf-8") as f:
s = f.read()
print(repr(s)) # '\ufeffSET NOCOUNT ON;'
但是,如果我们使用Python的“ utf-8-sig”编码读取文件,那么我们将获得删除了BOM字符的字符串
with open(r"C:\Users\Gord\Desktop\SQLQuery1.sql", encoding="utf-8-sig") as f:
s = f.read()
print(repr(s)) # 'SET NOCOUNT ON;'