[英]Add ODBC user DSN using python ctypes.windll.ODBCCP32.SQLConfigDataSource
I am trying to add new ODBC data source in python and found this code online which seem to work with python 2 (as other people mentioned but I have not tried) but does not work with python 3 (I am using 3.6). 我试图在python中添加新的ODBC数据源,并发现这个代码在线似乎与python 2一起工作(正如其他人提到但我没有尝试过)但是不能使用python 3(我使用的是3.6)。 The code runs without error but did not add new DSN to the system (always return 0). 代码运行时没有错误,但没有向系统添加新的DSN(始终返回0)。
I searched around and found some people mentioning it might be due to the encode issue, so I have tried to change the attribute part to bytes (nul.join(attrib)) with different encoding but none of them works. 我四处搜索,发现有人提到它可能是由于编码问题,所以我试图用不同的编码将属性部分更改为字节(nul.join(attrib)),但没有一个工作。
Here is part of the code: 以下是代码的一部分:
ODBC_ADD_DSN = 1 # Add data source, user DSN only
ODBC_CONFIG_DSN = 2 # Configure (edit) data source
ODBC_REMOVE_DSN = 3 # Remove data source
ODBC_ADD_SYS_DSN = 4 # add a system DSN
ODBC_CONFIG_SYS_DSN = 5 # Configure a system DSN
ODBC_REMOVE_SYS_DSN = 6 # remove a system DSN
def add_dsn(name, driver, **kw):
nul, attrib = '', []
kw['DSN'] = name
for attr, val in kw.items():
attrib.append('%s=%s' % (attr, val))
return ctypes.windll.ODBCCP32.SQLConfigDataSource(0, ODBC_ADD_DSN, driver, nul.join(attrib))
#
if __name__ == "__main__":
print (add_dsn('test', 'SQL Server', server='(local)', description = 'Testing'))
Can anyone help on how to resolve this issue or provide a solution to add new ODBC data sources using python. 任何人都可以帮助解决此问题或提供使用python添加新的ODBC数据源的解决方案。 Thanks! 谢谢!
To connect to SQL server using python 3 , I use the below statement and can get the data without any errors. 要使用python 3连接到SQL服务器,我使用下面的语句,可以获得没有任何错误的数据。
import pyodbc
import pandas as pd
cnxn = pyodbc.connect(driver='{SQL Server}', server='YourServer', database='YourDBName',
trusted_connection='yes')
cursor = cnxn.cursor()
then you can use pd.read_sql command to retrieve any data. 然后你可以使用pd.read_sql命令来检索任何数据。
print(pd.read_sql("SELECT * FROM [fruits]",cnxn))
Output from Database: 数据库输出:
fruiteater Fruit1 Fruit2 Fruit3 Fruit4 Fruit5 Fruit6
Aaron Orange Pear Apple None None None
Bob Apple Orange Blueberries Peach Mango Banana
Carter Pear Orange Apple None None None
David Blueberries None None None None None
Earnest Mango Orange Pear Apple Blueberries None
Frank Raspberries None None None None None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.