Python access sqlserver example

  • 2020-04-02 13:24:18
  • OfStack

Recently, I encountered problems with Python accessing SqlServer, which is summarized here.

Configure Python to access Sqlserver under Windows

Environment: Windows 7 + Sqlserver 2008

1. Download and install pyodbc

Download address: http://code.google.com/p/pyodbc/downloads/list

2, access to SqlServer


>>> import pyodbc
>>>cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=192.168.1.100\sql;DATABASE=testDB;UID=sa;PWD=myPassword')
>>>cursor = cnxn.cursor()
>>>cursor.execute("select * from Tb")

 

2. Configure Python to access SqlServer under Linux

Environment: CentOS 6.2 + Sqlserver 2008

1. Install freetds:


yum install freetds*


2. Install pyodbc:

yum install pyodbc

Modify odbc configuration:


vi /etc/odbcinst.ini

Add FreeTDS driver:


[SQL Server]
Description = FreeTDS ODBC driver for MSSQL
Driver = /usr/lib/libtdsodbc.so
Setup = /usr/lib/libtdsS.so
FileUsage = 1

3, test,


#python
>>> import pyodbc
>>>cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=192.168.1.100\sql;DATABASE=testDB;UID=sa;PWD=myPassword')
>>>cursor = cnxn.cursor()
>>>cursor.execute("select * from Tb")


Related articles: