Thursday, June 7, 2018

How do you connect to SQL Server using pyodbc?

pyodbc is an open source Python module that simplifies accessing ODBC databases. It implements the DB API 2.0 specs and has been filled with Python related items.

Connecting to SQL Server (SQL Server 2016 Sp2) is easy as long as you get the needed items correctly. Review the foolowing link if you landed on this page:

http://hodentekhelp.blogspot.com/2018/06/how-do-you-install-pyodbc.html
I assume you have installed:


  • pyodbc
  • Microsoft ODBC Driver for SQL Server


as described in the above link.

Now you need to create a DSN using the Microsoft ODBC which you installed.

Launch Microsoft ODBC Data Source Adminsitrator (x64) from search charm:



MicrosoftAdmin.png
We will create a User DSN. In the User DSN tabbed page shown click Add....






odbcAdmin1.png


In the Create New Data Source page choose ODBC Driver 17 for SQL Server.


odbcAdmin2.png

Click Finish.

In the Create a New Data Souce to SQL Server fill in the orginally empty boxes as shown (Of course you have to use the server details you have. For server the drop-down may or may not dsiplay your servers in which case you need to fill it in.


odbcAdmin3.png

Click Next> after filling up the page as shown above.
In the page that gets displayed as shown agree with the defaults.


odbcAdmin4.png


Click Next>.

Place check mark for Chnage the default database to: and using the drop-down pick a database (herein Northwind) on your server instance as shown.


odbcAdmin5.png

Accept other defaults and click Next>





odbcAdmin6.png
Click Finish.

The ODBC Microsoft SQL Server Setup page gets dispalyed ssummarizing the choices you made. Not that Mars is not supported.



odbcAdmin7.png

Click Test Data Source...

SQL Server ODBC Data Source Test
results page is displayed.


odbcAdmin8.png

Connecting to Northwind database on the server instnace Hodentek9\OHANA using pyodbc

Launch Python Shell and type in the following statements that connects to SQL Server. You create a cursor and fetch using SQL query in cursor.execute().


pyodbcConnect

No comments: