In the last blog I presented how to connect to Teradata
Database with teradata
python module. Today I’ll talk about how to connect to
SQL Server by python with following points:
- Required packages
- Connecting to SQL Server
- Checking databases in SQL Server
- Connecting to a specified database
- Extracting data with SQL query
Required packages
pyodbc
is an open source Python module that makes accessing ODBC databases
simple. It implements the DB API 2.0 specification but is packed with even more
Pythonic convenience.
Connecting to SQL Server
Let’s read this example line by line: the first two lines create a connection
to a SQL Server named “sqlprod” using SQL Server
as the connection method;
then we specify usename and password with UID
and PWD
.
Checking databases in SQL Server
After creating the connection to SQL Server, we can check databases in it.
“db” returns rich information of all databases which are contained in SQL Server, like name, database_id, source_database_id, create_date, etc.
Connecting to a specified database
By checking databases in SQL Server, we can now connect to a specified database.
Connecting to a database should specify the database-name in pyodbc.connect()
.
Extracting data with SQL query
To connect to “TABLE” of database “db1”, we need to precise the connection
“cnxn_db1” when execute SQL query with pandas.read_sql()
.
Reference
- M. Kleehammer, “pyodbc”, GitHub, 2017. [Online]. Available: https://github.com/mkleehammer/pyodbc
- “SQL Server Logo.png”, FANDOM, 2019. [Online]. Available: http://logos.wikia.com/wiki/Microsoft_SQL_Server