How to use the pyodbc.connect function in pyodbc

To help you get started, we’ve selected a few pyodbc examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mkleehammer / pyodbc / tests2 / freetdstests.py View on Github external
def setUp(self):
        self.cnxn   = pyodbc.connect(self.connection_string)
        self.cursor = self.cnxn.cursor()

        for i in range(3):
            try:
                self.cursor.execute("drop table t%d" % i)
                self.cnxn.commit()
            except:
                pass

        for i in range(3):
            try:
                self.cursor.execute("drop procedure proc%d" % i)
                self.cnxn.commit()
            except:
                pass
github cyberark / secretless-broker / test / connector / tcp / mssql / client / odbc_client.py View on Github external
}
CONN_TEMPLATE_STR = ";".join(
    [
        "DRIVER={{ODBC Driver 17 for SQL Server}}",
        "SERVER={server}",
        "DATABASE={database}",
        "UID={username}",
        "PWD={password}",
        "applicationintent={application_intent}",
    ],
)
conn_string = CONN_TEMPLATE_STR.format(**CONN_INFO)
SQL_ATTR_CONNECTION_TIMEOUT = 113
login_timeout = 2
connection_timeout = 2
cnx = pyodbc.connect(conn_string,
                     timeout=login_timeout,
                     attrs_before={
                         SQL_ATTR_CONNECTION_TIMEOUT: connection_timeout,
                     })
cursor = cnx.cursor()

if args.query.strip() == "":
    exit()

cursor.execute(args.query)
for row in cursor:
    print(row)
github AppEnlight / appenlight-client-python / appenlight_client / tests.py View on Github external
def test_odbc(self):
        try:
            import pyodbc
        except ImportError:
            return
        conn = pyodbc.connect(
            'Driver={MySQL};Server=127.0.0.1;Port=3306;Database=information_schema;User=test; Password=test;Option=3;')
        c = conn.cursor()
        c.execute(self.stmt)
        c.fetchone()
        c.close()
        conn.close()
        stats, result = get_local_storage(local_timing).get_thread_stats()
        assert len(result) == 2
github microsoft / msphpsql / test / Performance / run-perf_tests.py View on Github external
def connect( db ):
    """
    This module creates a connection to the given database
    Args:
        db (obj): database object
    Returns:
        A connection object to the given database       
    """
    return pyodbc.connect(
          driver="{ODBC Driver 13 for SQL Server}"
        , host=db.server_name
        , database=db.database_name
        , user=db.username
        , password=db.password
        , autocommit = True)
github datacenter / cloudcenter-content / services / sqlserverpaas / sqlserverpaas-arm.py View on Github external
try:
        print_log("Trying to deploy database server to resource group {}.".format(my_resource_group))
        deployment_async_operation = client.deployments.create_or_update(
            my_resource_group,
            'azure-sample',
            deployment_properties
        )
        deployment_async_operation.wait()
    except Exception as err:
        print_log("Error deploying database: {0}.".format(err))
        sys.exit(1)

    if 'cliqrDBSetupScript' in os.environ and len(os.environ['cliqrDBSetupScript']) > 0:
        print_log("Specified DB Setup Script downloaded to: {}. Running it...".format(os.environ['cliqrDBSetupScript']))
        try:
            cnxn = pyodbc.connect(
                "Driver={driver};Server=tcp:{serverName}.database.windows.net,{port};Database={masterDB};Uid={rootUser}@{serverName};Pwd={rootPass};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;".format(
                    serverName=serverName,
                    masterDB=masterDB,
                    rootUser=rootUser,
                    rootPass=rootPass,
                    driver="ODBC Driver 13 for SQL Server",
                    port=port
                ),
                autocommit=True
            )
            cursor = cnxn.cursor()
            with open(os.environ['cliqrDBSetupScript'], 'r') as dbScript:
                cursor.execute(dbScript.read())
        except Exception as err:
            print_log("Error running DB Setup Scrip: {0}.".format(err))
            sys.exit(1)
github OCA / connector / base_external_dbsource / base_external_dbsource.py View on Github external
def conn_open(self, cr, uid, id1):
        #Get dbsource record
        data = self.browse(cr, uid, id1)
        #Build the full connection string
        connStr = data.conn_string
        if data.password:
            if '%s' not in data.conn_string:
                connStr += ';PWD=%s'
            connStr = connStr % data.password
        #Try to connect
        if data.connector == 'cx_Oracle':
            os.environ['NLS_LANG'] = 'AMERICAN_AMERICA.UTF8'
            conn = cx_Oracle.connect(connStr)
        elif data.connector == 'pyodbc':
            conn = pyodbc.connect(connStr)
        elif data.connector in ('sqlite','mysql','mssql'):
            conn = sqlalchemy.create_engine(connStr).connect()
        elif data.connector == 'postgresql':
            conn = psycopg2.connect(connStr)

        return conn
github mark-hoffmann / fastteradata / fastteradata / file_processors / file_processors.py View on Github external
def connect_teradata(env, connector):

    env_n, env_dsn, env_short, usr, passw = load_db_info(env)

    if connector == "pyodbc":
        conn = odbc.connect('DRIVER={Teradata};VERSION=14.10;'+f"DBCNAME={env_n};DSN={env_dsn};UID={usr};PWD={passw};QUIETMODE=YES",autocommit=True)
        return(conn)

    elif connector == "teradata":
        udaExec = teradata.UdaExec(appName="Anomaly Detection", version='1.0', odbcLibPath="/opt/teradata/client/15.10/odbc_64/lib/libodbc.so", logConsole=False)
        session = udaExec.connect(method='odbc', system=env_n, username=usr, password=passw)
        return(session)
    else:
        raise ValueError("Wrong value error: Need to specify connector as either teradata or pyodbc")
github yhat / db.py / db / db.py View on Github external
server=self.hostname or "localhost",
                    database=self.dbname or ''
                )
                conn_str = ((self.username and self.password) and "{}{}".format(
                    base_con,
                    "User Id={username};Password={password};".format(
                        username=self.username,
                        password=self.password
                    )
                ) or "{}{}".format(base_con, "Trusted_Connection=Yes;"))

                try:
                    self.con = pyo.connect(conn_str)
                    self.cur = self.con.cursor()
                except:
                    self.con = pyo.connect(
                            driver=self.driver or "SQL Server",
                            server=self.hostname or "localhost",
                            port=self.port,
                            database=self.dbname or '',
                            uid=self.username,
                            pwd=self.password)
                    self.cur = self.con.cursor()
            elif HAS_PYMSSQL:
                if '\\' in self.hostname:
                    hostname = self.hostname
                elif hasattr(self, 'port'):
                    hostname = '{0}:{1}'.format(self.hostname, self.port)
                else:
                    hostname = self.hostname

                self.con = pymssql.connect(host=hostname,
github xbwei / Data-Mining-on-Social-Media / Access / Extract_Twitter_Search_Page.py View on Github external
Use bs4 to read webpage
'''

url_str = '' # fill in your search url from Twitter Search
response = request.urlopen(url_str)
html_data = response.read()
soup = BeautifulSoup(html_data,"html.parser")


'''
Connect to Access
'''
db_file = '' #define the location of your Access file

odbc_conn_str = 'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=%s' %(db_file) 
conn = pyodbc.connect(odbc_conn_str) 
cursor = conn.cursor() 

'''
use bs4 to extract data
'''

num_web = 0
num_tweet = 0
num_user = 0

for  li in soup.find_all("li", attrs = {"data-item-type":"tweet"}):
    print ("-----")
    print (li["data-item-id"])
    tweet_id = li["data-item-id"]
    for div_cont in li.find_all("div",attrs = {"class":"content"}):
        for div_header in div_cont.find_all("div",attrs = {"class":"stream-item-header"}):
github DataDog / dd-agent / checks.d / odbc.py View on Github external
timeout = int(instance.get('command_timeout',
                                   self.DEFAULT_COMMAND_TIMEOUT))

        host = instance.get('host')
        database = instance.get('database', self.DEFAULT_DATABASE)
        service_check_tags = [
            'host:%s' % host,
            'db:%s' % database
        ]

        try:
            if self._get_connector(instance) == 'adodbapi':
                rawconn = adodbapi.connect(self._conn_string_adodbapi(instance=instance),
                                       timeout=timeout)
            else:
                rawconn = pyodbc.connect(self._conn_string_odbc(instance=instance),
                                        timeout=timeout)
            self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.OK,
                               tags=service_check_tags)
            if conn_key not in self.connections:
                self.connections[conn_key] = {'conn': rawconn, 'timeout': timeout}
            else:
                try:
                    # explicitly trying to avoid leaks...
                    self.connections[conn_key]['conn'].close()
                except Exception as e:
                    self.log.info("Could not close adodbapi db connection\n{0}".format(e))

                self.connections[conn_key]['conn'] = rawconn
        except Exception as e:
            cx = "%s - %s" % (host, database)
            message = "Unable to connect to SQL Server for instance %s." % cx