python利用pymssql連接SQL

首先需要安裝pymssql模塊(http://linuxshow.blog.51cto.com/1572053/1407255)


配置下freetds

#cat /usr/local/freetds/etc/freetds.conf

#   $Id: freetds.conf,v 1.12 2007/12/25 06:02:36 jklowden Exp $
#
# This file is installed by FreeTDS if no file by the same
# name is found in the installation directory.  
#
# For information about the layout of this file and its settings,
# see the freetds.conf manpage "man freetds.conf".  

# Global settings are overridden by those in a database
# server specific section
[global]
       # TDS protocol version
;tds version = 4.2

# Whether to write a TDSDUMP file for diagnostic purposes
# (setting this to /tmp is insecure on a multi-user system)
;dump file = /tmp/freetds.log
;debug flags = 0xffff
# Command and connection timeouts
;timeout = 10

;connect timeout = 10

# If you get out-of-memory errors, it may mean that your client
# is trying to allocate a huge buffer for a TEXT field.  
# Try setting 'text size' to a more reasonable limit
text size = 64512

# A typical Sybase server#newadd
[test_db]
      host = 127.0.0.1
      port = 1433
      tds version = 8.0
      client charset = GBK



連接SQL服務器的代碼


import sys
import pymssql
class Mssql:
    def __init__(self, config):
        self.cf = config
    def __Connect(self):
        try:
            self.conn = pymssql.connect(host=self.cf['host'],user=self.cf['user'],password=self.cf['pwd'],database=self.cf['db'])
            cur = self.conn.cursor()
        except Exception, err:
            print "Error decoding config file: %s" % str(err)
            sys.exit(1)
        return cur
                                                                                                                                                                                                                                                                                                                                                                                               
    def select(self, sql):
        try:
            cur = self.__Connect()
            cur.execute(sql)
            rows = cur.fetchall()
            cur.close()
            self.conn.close()
            return rows
        except Exception, err:
            print "Error decoding config file: %s" % str(err)
            sys.exit(1)
    def insert(self, sql):
        try:
            cur = self.__Connect()
            cur.execute(sql)
            cur.close()
            self.conn.commit()
            self.conn.close()
        except Exception, err:
            print "Error decoding config file: %s" % str(err)
            sys.exit(1)
def main():
    config = {'host':'test_db','user':'test','pwd':'123456','db':'Testdb'}
    mssql = Mssql(config)
                                                                                                                                                                                                                                                                                                                                                                                               
    #select sql
    sql = "select * from test_table"
    rows = mssql.select(sql)
    #insert sql
    sql = "insert into test_table values('1','2','3')"
    mssql.insert(sql)
if __name__ == "__main__":
    main()


注:host裏test_db是調用freetds配置裏的,可以直接寫ip


下面是pymssql裏參數使用說明,如下:

1. pymssqlCnx類(用於連接Mssql數據庫)

pymssql.connect()來初始化連接類,它允許如下的參數。

dsn:連接字符串,主要用於與之前版本的pymssql兼容

user:用戶名

password:密碼

trusted:布爾值,指定是否使用windows身份認證登陸

host :主機名

database:數據庫

timeout:查詢超時

login_timeout:登陸超時

charset:數據庫的字符集

as_dict:布爾值,指定返回值是字典還是元組

max_conn:最大連接數


2. Method

autocommit(status)

布爾值,指示是否自動提交事務,默認的狀態是關閉的,如果打開,你必須調用commit()方法來提交事務。


close()
關閉連接



cursor()
返回遊標對象,用於查詢和返回數據
commit()

提交事務。


rollback()
回滾事務

pymssqlCursor類
用於從數據庫查詢和返回數據

rowcount

返回最後操作影響的行數。


connection

返回創建遊標的連接對象


lastrowid
返回插入的最後一行

rownumber
返回當前數據集中的遊標(通過索引)


3. 遊標方法

close()
關閉遊標

execute(operation)

執行操作


execute(operation, params)

執行操作,可以提供參數進行相應操作


executemany(operation, params_seq)

執行操作,Params_seq爲元組

fetchone()
在結果中讀取下一行

fetchmany(size=None)
在結果中讀取指定數目的行


fetchall()
讀取所有行

nextset()
遊標跳轉到下一個數據集


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章