Connect to Linked Server via SQL Server pyodbc connection?

半城伤御伤魂 提交于 2020-08-09 12:27:57

问题


I can currently connect to my SQL Server and query any database I want to directly.

The problem is when I want to query a linked server. I cannot directly reference the linked servers name in the connect() method and I have to connect to a local database first and then run an OPENQUERY() against the linked server.

This seams like a odd work around. Is there a way to query the linked server directly (from my research you cannot connect directly to a linked server) or at least connect to the server without specifying a database where I can then run the OPENQUERY() for anything without having to first connect to a database?

Example of what I have to do currently:

import pyodbc

ex_value = "SELECT * FROM OPENQUERY(LinkedServerName,'SELECT * FROM LinkedServerName.SomeTable')"
# I have to connect to some local database on the server and cannot connect to linked server initially.
odbc_driver, server, db = '{ODBC Driver 17 for SQL Server}', 'MyServerName', 'LocalDatabase'

with pyodbc.connect(driver=odbc_driver, host=server, database=db, trusted_connection='yes') as conn:
    conn.autocommit = False
    cursor = conn.cursor()
    cursor.execute(ex_value)
    tables = cursor.fetchall()

    for row in tables:
        print('Row: {}'.format(row))

    cursor.close()

回答1:


As Sean mentioned, a linked server is just a reference to another server that's stored within the local server.

You do not need to manage 100+ user credentials though. If you have the users using Windows auth, and you have Kerberos working between the servers, the linked server can just impersonate you when it connects to the other server via the linked server definition.

Then you can use either 4 part names to refer to objects on the other server, or use OPENQUERY when you want more control over what gets executed where.

Finally, if they're both SQL Servers and both use the same collation, make sure you set the linked server option to say they are collation compatible. That can make a major difference to your linked server performance. I regularly see systems where that isn't set and it should be.



来源:https://stackoverflow.com/questions/58614999/connect-to-linked-server-via-sql-server-pyodbc-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!