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)

        测试结果如下:

 Connect Successful!!!
 select_sql is:  SELECT * FROM ******
 Total Records Number is:  14750
 [Finished in 3.3s]

        其他的功能也都测试了,这里就不列举了,感兴趣的话可以试试。

       数据库的连接配置换成自己的就行了。

       欢迎交流。

 

 

你可能感兴趣的:(软件工具使用,编程技术)