Created
August 30, 2016 16:43
-
-
Save bixb0012/d97cb412f98aa427b4dfbdc995fb6510 to your computer and use it in GitHub Desktop.
PyODBC: Connect to Database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Reference: 1) https://mkleehammer.github.io/pyodbc | |
# 2) https://docs.python.org/3/library/re.html#regular-expression-objects | |
import pyodbc | |
import re | |
driver_regexes = { | |
"mssql": ("ODBC Driver.*SQL Server", "SQL Server Native Client.*"), | |
"oracle": ("Oracle in.*") | |
} | |
odbc_keywords = { | |
"mssql": { | |
"SERVER": None, | |
"DATABASE": None, | |
"TRUSTED_CONNECTION": "YES", # 'NO' when specifiying UID and PWD | |
"UID": None, | |
"PWD": None | |
} | |
} | |
# Example 1: Connecting and querying SQL Server | |
dbms = "mssql" | |
sql = # SQL SELECT statement for testing | |
conn_string = ";".join( | |
"{}={}".format(k,v) for k,v in odbc_keywords[dbms].items() if v | |
) | |
available_drivers = "\n".join(pyodbc.drivers()) | |
for regex in driver_regexes[dbms]: | |
match = re.search(regex, available_drivers) | |
if match: | |
conn_string += ";DRIVER={" + match.group() + "}" | |
break | |
conn = pyodbc.connect(conn_string) | |
cur = conn.execute(sql) | |
print next(cur) | |
# |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment