Skip to content

Instantly share code, notes, and snippets.

@bixb0012
Created August 30, 2016 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bixb0012/d97cb412f98aa427b4dfbdc995fb6510 to your computer and use it in GitHub Desktop.
Save bixb0012/d97cb412f98aa427b4dfbdc995fb6510 to your computer and use it in GitHub Desktop.
PyODBC: Connect to Database
# 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