python连接SQLServer数据库,执行给定的查询SQL语句,并返回查询结果数据

import sys
import pymssql
reload(sys)
sys.setdefaultencoding("utf-8")
 
 
#数据库连接配置
config_dict={
            ‘user‘:‘sa‘,
            ‘password‘:‘‘,
            ‘host‘:‘127.0.0.1‘,
            ‘database‘:‘pawn2007‘
            }
 
 
def SQLServer_connect(config_dict):
    ‘‘‘
    SQLServer 数据库连接
    ‘‘‘
    connect=pymssql.connect(**config_dict)
    print ‘Connect Succesful!!!‘
    return connect
 
 
def executeSQL(config_dict,one_sql):
    ‘‘‘
    执行给定的SQL语句
    ‘‘‘
    rowcount=None
    try:
        connect=SQLServer_connect(config_dict)
        cursor=connect.cursor() 
        cursor.execute(one_sql)
        num=cursor.rownumber
        count=cursor.rowcount
        print ‘Cursor Num is: ‘,num
        print ‘Cursor Count is: ‘,count
        rowcount=cursor.fetchone()[0]
        print ‘Total Records Num is: ‘,rowcount
    except Exception,e:
        print ‘executeSQL ERROR: ‘,e
    finally:
        connect.close()
    return rowcount
 
  
if __name__==‘__main__‘:
    one_sql="SELECT COUNT(*) FROM TABLE"
    executeSQL(config_dict,one_sql)

相关推荐