python利用pymssql连接SQL

发布时间:2019-09-16 07:15:41编辑:auto阅读(1629)

    首先需要安装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()
    游标跳转到下一个数据集


关键字