• Python数据库模块pymssql连接SQLServer数据库操作


    
    Python数据库模块pymssql连接SQLServer数据库操作详解
    
    
    最近需要使用到SQLServer数据库,之前一直使用的是MySQL数据库,我比较喜欢使用Python,之前一直使用的是pymysql作为数据库的操作工具,现在需要换成pymssql了,使用方法大概相同,查资料的过程中发现网上很多资料讲的都是部分的,这里总结了一下最近的操作,详细地给出了操作代码,相信很好看明白,希望能帮到需要的人。
    
          下面是具体的实现:
    
    #!usr/bin/env python
    # encoding:utf-8
     
     
    '''
    __Author__:沂水寒城
    功能:使用pymssql连接SQLServer测试使用
    '''
     
    import sys
    import logging
    import pymssql
     
    reload(sys)
    sys.setdefaultencoding("utf-8")
     
     
    LOG_FORMAT="%(asctime)s - %(levelname)s - %(message)s"
    DATE_FORMAT="%m-%d-%Y %H:%M:%S %p"
    logging.basicConfig(filename='SQLServer.log',level=logging.DEBUG,format=LOG_FORMAT,
                        datefmt=DATE_FORMAT)
     
     
    #数据库的;连接配置信息
    config_dict={
                'user':'你的用户名',
                'password':'你的密码',
                'host':'你要连接的host地址',
                'database':'你要操作的数据库'
                }
     
     
     
    tablename='你要操作的表名'
     
     
    def SQLServer_connect(config_dict):
        '''
        SQLServer 数据库连接
        '''
        connect=pymssql.connect(**config_dict)
        print 'Connect Successful!!!'
        return connect
     
     
    def select_k_records(config_dict,tablename,topk=100):
        '''
        从SQLServer中选取前k条记录
        '''
        try: 
            connect=SQLServer_connect(config_dict)
            cursor=connect.cursor()  
            #统计记录数量
            result=[]
            cursor=connect.cursor() 
            select_sql='SELECT * FROM %s' %tablename
            print 'select_sql is: ',select_sql
            cursor.execute(select_sql)
            row=cursor.fetchone()
            while row:
                if len(result)<topk:
                    result.append(row)
                    row=cursor.fetchone()
                    print row
                else:
                    break
            print 'result: '
            print result
            connect.close()
            cursor.close()
        except Exception, e:
            print "elect_sql error: " + e
        finally:
            connect.close()
        return result
     
     
    def create_new_table(config_dict,tablename):
        '''
        创建表
        '''
        connect=SQLServer_connect(config_dict)
        cursor=connect.cursor() 
        #cursor.execute('select * into WZ_cgb_test from WZ_OA_PUBLICOPINION where 1=2')
        #省略号替换成自己的字段信息即可
        cursor.execute("""
        CREATE TABLE %s (
            id VARCHAR(32) NOT NULL,
            name VARCHAR(255) NULL,
            ......
            PRIMARY KEY(id)
        )""" %tablename
        )
        connect.commit()  #记得提交数据库事物操作
        connect.close()
        cursor.close()
     
     
    def delete_record(config_dict,delete_sql):
        '''
        从 SQLServer 中删除数据记录
        '''
        try:
            connect=SQLServer_connect(config_dict)
            cursor=connect.cursor()  
            cursor.execute(delete_sql)
            connect.commit()
            print 'DeleteOperation Finished!!!'
        except Exception, e:
            print "delete_sql error: " + e
        finally:
            connect.close()
     
     
    def count_records_num(config_dict,tablename):
        '''
        统计SQLServer中的数据记录数量
        '''
        try: 
            connect=SQLServer_connect(config_dict) 
            cursor=connect.cursor() 
            totalNum=cursor.rowcount
            print 'Total Records Number is: ',str(totalNum)
            connect.close()
            cursor.close()
        except Exception, e:
            print "count_sql error: " + e
        finally:
            connect.close()
        return len(result)
     
     
    def insert_record(config_dict,insert_sql):
        '''
        向SQLServer中插入数据
        '''
        try:
            connect=SQLServer_connect(config_dict)
            cursor=connect.cursor() 
            cursor.execute(insert_sql)
            connect.commit()
            print 'InsertOperation Finished!!!'
        except Exception, e:
            print "insert_sql error: " + e
        finally:
            connect.close()
     
     
     
    if __name__ == "__main__":
        count_records_num(config_dict,tablename)
        #select_k_records(config_dict,tablename,topk=10)
     
     
            测试结果如下:
    
     Connect Successful!!!
     select_sql is:  SELECT * FROM ******
     Total Records Number is:  14750
     [Finished in 3.3s]
            其他的功能也都测试了,这里就不列举了,感兴趣的话可以试试。
    
           数据库的连接配置换成自己的就行了。
    
    
    
    
    
  • 相关阅读:
    C# 集合类 Array Arraylist List Hashtable Dictionary Stack Queue
    Javascript在IE与Firefox下的差异
    ASP.NET状态服务及session丢失问题解决方案总结
    在Silverlight中读取指定URL图片包数据
    Cookie记住滚动条
    IHttpModule 与IHttpHandler的区别
    页面内容随滚动条滚动动态载入JavaScript脚本。
    Asp.net MVC Action大全(转)
    简单的css横向菜单
    实线表格Html
  • 原文地址:https://www.cnblogs.com/ludundun/p/13392248.html
Copyright © 2020-2023  润新知