利用python簡化sql server數據導入導出


 
      前面我們介紹了如何  使用sqlserver的BCP命令 進行數據的導出和導入。使用這個命令一個不足的地方的是不能對整個數據庫進行一次性操作。如果表很多的時候就要一個個命令操作,不可謂不麻煩!
  正好最近在學習python,於是打算用python實現了一個簡化bcp操作的程序。點擊程序后就會自動將指定的數據庫所有的表的備份數據放到一個特定的目錄下。當然,程序也提供對應的自動化導入功能~~
 
源碼:
 
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#-------------------------------------------------------------------------------
# Name:        導出數據庫數據.py
# Purpose:
#
# Author:      SQ1000
#
# Created:     08-02-2012
#-------------------------------------------------------------------------------

import os
import pymssql
import sys

class MSSQLHelper :
     "" "
    對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 = MSSQLHelper(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.encode( "utf8"))
        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.encode( "utf8"))
         self.conn.commit()
         self.conn.close()


def RemoveDirectory (top) :
     while 1 :
         if os.path.exists(top) :
             if len( os.listdir(top)) == 0 :
                 os.rmdir (top)
                 break
             else :
                 for root, dirs, files in os.walk(top, topdown = False) :
                     for name in files :
                         os.remove( os.path.join(root, name))
                     for name in dirs :
                         os.rmdir( os.path.join(root, name))
         else :
             break

def export(db,user,password) :
     "" "導出數據庫" ""
     #得到當前腳本的執行目錄
    currentDirectory = os.getcwd()

     #查看是否已經存在備份目錄,如果有則刪除,沒有則新建目錄
    backUpDirectory = "%s\\%s" %( currentDirectory,db + "Backup")
     if os.path.exists(backUpDirectory) :
        RemoveDirectory(backUpDirectory)
         os.mkdir(backUpDirectory)
     else :
         os.mkdir(backUpDirectory)

     #得到要到處的數據庫的所有表
    ms = MSSQLHelper(host = "localhost",user =user,pwd =password,db =db)
     for (name,) in ms.ExecQuery( "select name from sysobjects where xtype='U'") :
        currentTablePath = "%s\\%s.txt" %(backUpDirectory,name)
        r = os.popen( 'BCP %s..%s out %s -c -U"%s" -P"%s"' % (db,name,currentTablePath,user,password))
         print r.read()
        r.close()

def inport(db,user,password) :
     "" "導入數據庫" ""
     #得到當前腳本的執行目錄
    currentDirectory = os.getcwd()

     #查看是否已經存在備份目錄,如果有則刪除,沒有則新建目錄
    backUpDirectory = "%s\\%s" %( currentDirectory,db + "Backup")
     if os.path.exists(backUpDirectory) :
         #得到要到處的數據庫的所有表
        ms = MSSQLHelper(host = "localhost",user =user,pwd =password,db =db)
         for (name,) in ms.ExecQuery( "select name from sysobjects where xtype='U'") :
            currentTablePath = "%s\\%s.txt" %(backUpDirectory,name)
            r = os.popen( 'BCP %s..%s in %s -c -U"%s" -P"%s"' % (db,name,currentTablePath,user,password))
             print r.read()
            r.close()


def main() :

    db = "PythonWeiboStatistics"
    user = "sa"
    password = "123456"

     #這邊可以根據不同的參數選擇不同的操作
     #我是使用了兩個文件,一個是導入一個導出
    export(db,user,password)

if __name__ == '__main__' :
    main()

     print u "\n導出完成...\n回車鍵退出"
     raw_input()
 
 
因為要獲得一個數據庫中所有的表,所以我使用了 pymssql來進行數據庫操作並進行理論簡單的封裝,形成了MSSQLHelper類。具體的pymssql的下載和用法大家可以到網上進行搜索。思路很簡單:
  • 導入的時候查看是否已經存在特定的導出目錄,如果存在則刪除該目錄下所有的文件
  • 利用pymssql讀取指定數據庫中所有的表名字,對每個表進行bcp命令
導入的功能則是省去了刪除已存在文件那個操作,其他都差不多。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM