将Ubuntu上的python3连接到SQL Server 2014

时间:2017-02-16 11:03:12

标签: python sql-server python-3.x ubuntu pyodbc

我正在尝试使用SQL Server的ODBC驱动程序13在Python 3.5脚本中检索Linux服务器(Ubuntu 16.04.2)上的SQL数据。在Windows上运行SQL Server和Python上的脚本很顺利。在Linux中使用Python运行脚本会引发SQL Server语法错误:

pyodbc.ProgrammingError:(' 42000'," [42000] [Microsoft] [SQL Server的ODBC驱动程序13] [SQL Server]' 0x107c'附近的语法不正确。(102)(SQLExecDirectW)")

当我添加或删除列时,它会更改' 0x107c'一个不同的角色暗示它不是一个非法的角色,而是几个。使用更多有限的列,脚本甚至可以运行(排除[Order Type text]和[Order Nr])。这使我怀疑字符集转换出了问题。我做错了什么,我该如何解决?

Python3.5:

import pandas as pd
import pyodbc

#Set parameters
sql_file = 'file.sql'

#Define methods
def SQLDataToDataframe(filename):
    fd = open('file.sql','r')
    content = fd.read()
    fd.close()
df = pd.read_sql(content, connection)
return df

#Import Data from SQL
connection = pyodbc.connect('Driver={ODBC Driver 13 for SQL Server};'
                            'Server=Server;'
                            'Database=DB;'
                            'uid=User;pwd=Password')

 dataframe = SQLDataToDataframe(sql_file)

file.sql:

SELECT [ID]
  ,[Company Code]
  ,[Description]
  ,[Order Category]
  ,[Order Category Text]
  ,[Order Type]
  ,[Order Type text]
  ,[Order Nr]
FROM [TABLE]

1 个答案:

答案 0 :(得分:2)

解决方案以供将来参考。不要在Linux上使用pyodbc连接到MS SQL Server。请改用pymssql。这里的说明:https://docs.microsoft.com/en-us/sql/connect/python/pymssql/step-1-configure-development-environment-for-pymssql-python-development