Search code examples
pythonsql-serverpypyodbc

"Error Locating Server/Instance Specified" when connecting to SQL Server


I'm using python 2.7 have the code below to connect sql instances

class SqlConnector:
    def __init__(self, driver, sqlserver_ip, database, **kwargs):
        if 'port' in kwargs:
            conn_string = 'DRIVER='+ driver + ';SERVER='+ sqlserver_ip +';PORT=' + kwargs['port'] + ';DATABASE=' + database + ';trusted_connection=yes;'
        else:
            conn_string = 'DRIVER='+ driver + ';SERVER='+ sqlserver_ip + ';DATABASE=' + database + ';trusted_connection=yes;'
        print conn_string
        self.conn = pypyodbc.connect(conn_string)
        self.cur = self.conn.cursor()

    def __enter__(self):
        return self

    def query(self, query_string):
        self.cur.execute(query_string)
        return

    def get_all_table_columns(self):
        columns = [column[0] for column in self.cur.description]
        return columns

    def get_all_table_rows(self):
        rows = self.cur.fetchall()
        return rows

    def __repr__(self):
        conn_string = 'DRIVER='+ driver + ';SERVER='+ sqlserver_ip + ';DATABASE=' + database + ';trusted_connection=yes;'
        return conn_string

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.conn or self.cur:
            # close cursor
            self.cur.close()
            # close connection
            self.conn.close()

My SQL instance is like "hostname\PEWKA", but error below saying

(u'08001', u'[08001] [Microsoft][SQL Server Native Client 11.0]SQL Server Network Interfaces: Error Locating Server/Instance Specified [xFFFFFFFF]. ')

is this the correct way to connect SQL instance using pypyodbc? can't really find too much info out of it.

Anyone can shed some light will be very appreciated.

Thanks


Solution

  • Connecting by instance name

    Provide the server name and instance name separated by a backslash, e.g., SERVER=hostname\PEWKA. Do not supply a port number. If the SQL Server instance is on a remote machine then the SQL Server Browser service must be running on that machine.

    Connecting by port number

    Provide the server name and port number separated by a comma, e.g., SERVER=hostname,49242. Do not supply the instance name. Note also that the SQL Server ODBC drivers do not support a PORT= parameter in the connection string.