我想使用 Pyodbc 连接到 SQL 服务器,但它总是显示相同的错误。
这是我到目前为止的代码:
import pyodbc
try:
conn = pyodbc.connect('DRIVER = {SQL Server};SERVER=master;DATABASE=Clinica;UID=djimenez;PWD=PRIVATE')
print ("Conexion succesful")
except Exception as ex:
print(ex)
显示错误为:
('IM002', '[IM002] [unixODBC][Driver Manager]Data source name not found and no default driver specified (0) (SQLDriverConnect)')
我对这类东西还是新手,所以我不知道这意味着什么。我使用终端并查看了
where unixODBC
它说没有找到。我尝试安装它,但它说它已经安装了。我搜索了我的问题,然后找到了 MarkLogic。我尝试下载它,但显然它与 Mac M1 不兼容,这就是我所在的位置。所以我被困住了,不知道该怎么办..请问有什么帮助吗?
有多种方法可以让 Python 与 SQL Server 交互。
# connect to SQL Server
import pyodbc
from sqlalchemy import create_engine
driver= '{SQL Server Native Client 11.0}'
conn_str = (
r'DRIVER={SQL Server};'
r'SERVER=LAPTOP-CEDUMII6;'
r'DATABASE=TestDB;'
r'Trusted_Connection=yes;'
)
cnxn = pyodbc.connect(conn_str)
cursor = cnxn.cursor()
cursor.execute('SELECT * FROM Employee')
# print contents of table
for row in cursor:
print('row = %r' % (row,))
相关资源:
https://github.com/mkleehammer/pyodbc/wiki/Connecting-to-SQL-Server-from-Windows
或者……
# push dataframe to table in SQL Server
engine = create_engine(cnxn, fast_executemany=True)
df_append.to_sql('your_table', engine, index=False, if_exists='append')
此错误告诉您缺少驱动程序。简而言之,该连接字符串用于建立与所需服务器的连接。在字符串的第一部分中,您将连接定向到驱动程序所在的位置。您缺少驱动程序,或者当您下载驱动程序时,您只下载了驱动程序本身,并且您将不得不更新“驱动程序配置文件”,因为缺少更好的术语。任何 ODBC 连接都将利用此文件来获取驱动程序的位置。对于我的 Mac,它位于
/usr/local/etc/odbcinst.ini
,如果您要连接到 Microsoft SQL 服务器,您的连接字符串将像 DRIVER = {ODBC Driver 17 for SQL Server}....
一样开始。这意味着在 odbcinst.ini
中您将看到此条目
[ODBC Driver 17 for SQL Server] --> This matches name in the connection string
Description=Microsoft ODBC Driver 17 for SQL Server
Driver=/usr/local/lib/libmsodbcsql.17.dylib
UsageCount=1
现在,在您的情况下,当您转到文件时,您将看不到
{SQL Server}
来修复此问题,请进入您的文件并手动添加配置,并确保您指向驱动程序所在的位置。那么您的错误至少会在该部分得到解决。