Python access to SQL Server installation, configuration, code samples

Source: Internet
Author: User
Tags sybase database

FreeTDS is able to connect MS SQL Server and Sybase database with Linux and UNIX, TDS means "table column data Flow"


To install the GCC components:

Yum install-y gcc

Otherwise configure when the error:

Configure:error:no acceptable C compiler found in $PATH



Install Freetds-dev under Linux:

Download Source:

http://mirrors.ibiblio.org/freetds/stable/

Freetds-stable.tgz

http://www.freetds.org/


After extracting from any directory:

./configure--prefix=/usr/local/freetds--with-tdsver=8.0

Make

sudo make install


Configuration file:/usr/local/freetds/etc/freetds.conf

Add to:

[mssql2005]

Host = x.x.x.x

Port = 1433

TDS Version = 8.0

Client CharSet = UTF-8



Test:

#/usr/local/freetds/bin/tsql-s mssql2005-h x.x.x.x-p 1433-u myuser-p mypassword

1> SELECT * from MyDB. MyTable

2> Go

(Query results can be obtained normally)



Download Python setuptools-git

https://pypi.python.org/pypi/setuptools-git/

Unzip to any directory and run into directory:

Python setup.py Install


Download and install Pymssql:

Https://pypi.python.org/pypi/pymssql/2.1.1#downloads

Pymssql-2.1.1.tar.gz

Unzip to any directory and run into directory:

Python setup.py Install


To increase the LIB path:

Export Ld_library_path= $LD _library_path:/usr/local/freetds/lib/


You can import pymssql in Python


To increase the bin path:

Vi/root/.bashrc

Add content as follows:

Export Freetds=/usr/local/freetds

Export $PATH = "$PATH: $FREETDS/bin"

To make it effective immediately:

Source/root/.bashrc


(end)


code example:

#coding =utf-8 #!/usr/bin/env pythonimport pymssqlimport configparserclass mssql:     def __init__ (self):         cf =  configparser.configparser ()         cf.read ("mssql.conf")          self.host = cf.get ("DB", "host")          self.user = cf.get ("DB", "user")          self.pwd = cf.get ("DB", "pwd")         self.db =  cf.get ("db", "db")                 def __getconnect (self):         "" "         get connetion info        response:  conn.cursor ()          "" "         #if  not self.db:         #    raise (NameError, "no db conf  file found ")              self.conn  = pymssql.connect (Host=self.host,user=self.user,password=self.pwd,database=self.db,timeout=5,login_ timeout=2,charset= "UTF8")         cur = self.conn.cursor ()         if not cur:             raise (Nameerror, "fail connecting to db")          else:             return cur    # #verify  DB connection    def  VerifyConnection (self):         try:             if self.host== ':                 return False             conn = pymssql.connect (Host=self.host,user=self.user,password=self.pwd,database=self.db, timeout=1,login_timeout=1,charset= "UTF8")              return True        except:             return false    def execquery (Self,sql ):         "" "        execute  query        get a list including tuple,  elements of list are row of record, elements of tuple is fields         demo                 ms = mssql (host= "localhost", user= "sa", pwd= "123456", db= "Pythonweibostatistics")                 reslist =  ms. ExecQuery ("Select id,nickname from weibouser")                  for  (Id,nickname)  in resList:                     print  str (ID),nickname         "" "         cur = self.__getconnect ()         cur.execute (SQL )   &NBSp;     reslist = cur.fetchall ()           #resList  = cur.description         #close   Connection after querying        self.conn.close ()          return reslist    def execnonquery ( Self,sql):         "" "         execute no query        demo             cur = self.__getconnect ()              cur.execute (SQL)              self.conn.commit ()              self.conn.close ()   &NBsp;      "" "        cur = self.__ GetConnect ()         cur.execute (SQL)          self.conn.commit ()         self.conn.close ()      def execstoreproduce (self,sql):         "" "         execute query         get a list including tuple, elements of list are row  of record, elements of tuple is fields         demo:                ms  = mssql (host= "localhost", user= "sa", pwd= "123456", db= "Pythonweibostatistics")                   reslist = ms. ExecQuery ("Select id,nickname from weibouser")                  for  (Id,nickname)  in resList:                     print  str (ID),nickname         "" "         cur = self.__getconnect ()         cur.execute (SQL )         reslist = cur.fetchall ()          self.conn.commit ()          #close   Connection after querying        self.conn.close ()          return reslistdef main(): sqlquery= "Select * from mydb. MyTable "Sqlconn=mssql () res=sqlconn. ExecQuery (sqlquery) for data in res:print dataif __name__== ' __main__ ': Main ()

Configuration file mssql.conf:

[Db]host=x.x.x.xdb=mydbuser=myuserpwd=mypassword


Python access to SQL Server installation, configuration, code samples

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.