Create a jTDS connection string in Python

前端 未结 1 1030
抹茶落季
抹茶落季 2021-01-22 15:22

I\'m trying to establish a jTDS connectivity using Python. Can anyone please help me in accomplishing that?

From the SQL Server, I generally connect using the below conn

相关标签:
1条回答
  • 2021-01-22 15:53

    If you are specifically trying to connect to MS SQL Server using jTDS as opposed to ODBC, then you can use the jaydebeapi python package.

    See the following code (Python 3):

    import sys
    import jaydebeapi
    
    
    def main():
        try:
            # jTDS Driver.
            driver_name = "net.sourceforge.jtds.jdbc.Driver"
    
            # jTDS Connection string.
            connection_url = "jdbc:jtds:sqlserver://<server_hostname>:<port>/<database_name>"
    
            # jTDS Connection properties.
            # Some additional connection properties you may want to use
            # "domain": "<domain>"
            # "ssl": "require"
            # "useNTLMv2": "true"
            # See the FAQ for details http://jtds.sourceforge.net/faq.html
            connection_properties = {
                "user": "username",
                "password": "password",
            }
    
            # Path to jTDS Jar
            jar_path = "<path_to>\\jtds-1.3.1.jar"
    
            # Establish connection.
            connection = jaydebeapi.connect(driver_name, connection_url, connection_properties, jar_path)
            cursor = connection.cursor()
    
            # Execute test query.
            cursor.execute("select 1 as test_connection")
            res = cursor.fetchall()
            if res:
                print(str(res))  # Should print [(1,)]
    
        except Exception as err:
            print(str(err))
    
    
    if __name__ == "__main__":
        sys.exit(main())
    

    Prior to this, you need to complete the following:

    1. Download and install JDK/JRE from here
    2. pip install jaydebeapi or download from here
    3. Download jtds from here
    4. Update connection_url, connection_properties, jar_path.
    0 讨论(0)
提交回复
热议问题