【发布时间】:2018-02-06 04:28:07
【问题描述】:
我有一个使用 MS Sql Server Management Studio 保存为 .sql 文件的查询:
select distinct *
from bom.SalesBOMSampleExplosion b
我尝试使用 pyodbc 包通过 python 读取文件。我的其他查询使用几乎相同的设置成功运行,除了这个查询。 这是我使用的python代码:
将熊猫导入为 pd 将pyodbc导入为数据库
def sql_reader(qry_file, server_name, database):
server = db.connect(str('DRIVER={SQL Server};SERVER='+server_name+';DATABASE='+database+';'))
qry = open(qry_file,'r').read()
data = pd.read_sql(qry,server)
return data
但是当我使用该函数并调用sql文件时:
server = 'sampleserver'
db = 'sampledb'
Data = sp.sql_reader(os.path.join(qry_path, 'Data.sql'), server_name=server, database=db)
以下错误信息不断出现:
Traceback (most recent call last):
File "C:/Users/Documents/landlordlady/python codes/test.py", line 8, in <module>
QPVData = sp.sql_reader(os.path.join(qry_path, '8-28 qpv test.sql'), server_name=server, database=db)
File "C:\Users\Documents\landlordlady\python codes\sql_processor.py", line 30, in sql_reader
data = pd.read_sql(qry,server)
File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\io\sql.py", line 399, in read_sql
chunksize=chunksize)
File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\io\sql.py", line 1436, in read_query
cursor = self.execute(*args)
File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\io\sql.py", line 1413, in execute
raise_with_traceback(ex)
File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\compat\__init__.py", line 340, in raise_with_traceback
raise exc.with_traceback(traceback)
File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\io\sql.py", line 1401, in execute
cur.execute(*args)
pandas.io.sql.DatabaseError: Execution failed on sql 'ÿþ
s e l e c t d i s t i n c t *
f r o m b o m . S a l e s B O M S a m p l e E x p l o s i o n b
': ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near 'e'. (102) (SQLExecDirectW)")
Process finished with exit code 1
我很困惑!这个错误在说什么语法?!
【问题讨论】:
-
您似乎有一些编码问题。也许 utf-16 应该是 utf-8 的地方,或者你可能在某个时候不小心在你的字符串中插入了空格,或者其他的东西。
-
@user2357112 那么我该如何解决这个问题?
-
您使用什么编辑器创建 .sql 文件?另外为了进一步澄清,您可以添加您使用的python代码吗?
-
@RageCage 我已经编辑了我的帖子!并且我还使用 Sql server management studio 编写了 sql 文件。
-
您能否尝试将实际查询 (
select distinct * from bom.SalesBOMSampleExplosion b) 复制并粘贴到 Windows 记事本中并将其另存为单独的文件,然后读取该文件?这可能有助于我们对编码问题进行三角测量。
标签: python sql-server pyodbc