Windows and Linux using Python access to SqlServer methods
- 2020-04-02 14:37:42
- OfStack
I often use Python to write demos to verify the feasibility of the scheme. Recently, I encountered the problem of Python access to 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")
Here is just a simple demo to verify the feasibility, I hope it is helpful to you.