Python 은 pymssql 을 이용 하여 my sql 데이터 베 이 스 를 방문 합 니 다.

#coding=utf8
#!/usr/bin/env python
#-------------------------------------------------------------------------------
# Name: pymssqlTest.py
# Purpose:    pymssql ,       :http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql
#
# Author: scott
#
# Created: 04/02/2012
#-------------------------------------------------------------------------------

import pymssql
import sys
import decimal

reload(sys)
sys.setdefaultencoding( "utf8" )

class MSSQL:
    """
     pymssql     
    pymssql ,       :http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql
         ,   Sql Server Configuration Manager   TCP/IP    

      :

    """

    def __init__(self,host,user,pwd,db):
        self.host = host
        self.user = user
        self.pwd = pwd
        self.db = db

    def __GetConnect(self):
        """
              
          : conn.cursor()
        """
        if not self.db:
            raise(NameError,"         ")
        self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8")
        cur = self.conn.cursor()
        if not cur:
            raise(NameError,"       ")
        else:
            return cur

    def ExecQuery(self,sql):
        """
              
                tuple list,list       ,tuple           

            :
                ms = MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics")
                resList = ms.ExecQuery("SELECT id,NickName FROM WeiBoUser")
                for (id,NickName) in resList:
                    print str(id),NickName
        """
        cur = self.__GetConnect()
        cur.execute(sql)
        resList = cur.fetchall()

        #           
        self.conn.close()
        return resList

    def ExecNonQuery(self,sql):
        """
               

            :
            cur = self.__GetConnect()
            cur.execute(sql)
            self.conn.commit()
            self.conn.close()
        """
        cur = self.__GetConnect()
        cur.execute(sql)
        self.conn.commit()
        self.conn.close()

좋은 웹페이지 즐겨찾기