Восстановление резервной копии сервера SQL через python начинается, но не завершается - PullRequest
0 голосов
/ 23 апреля 2019

Я пытаюсь восстановить резервную копию SQL сервера, используя python.У меня есть встроенный пользовательский интерфейс в Tkinter, который принимает путь к файлу и другие детали, такие как имя сервера, имя базы данных и т. Д. Для тестирования я просто использую localhost.Есть два файла, которые я разработал.Один называется tool.py с пользовательским интерфейсом, а другой - с именем Restorebackup.py, в котором есть логика для восстановления базы данных.Когда вы запускаете файл tool.py и нажимаете кнопку запуска, он запрашивает путь к файлу .dat_bak или .bak, который вы хотите восстановить.После выбора файла .dat_bak вы ждете некоторое время и получаете сообщение «Резервная копия восстановлена».Я иду в SQL Server Management Studio и вижу базы данных в localhost.Это показывает, что резервное копирование восстанавливается с синей стрелкой.К сожалению, это никогда не завершается и застревает там навсегда.Когда я просто запускаю Restorebackup.py путем жесткого кодирования filepath и других значений, он прекрасно восстанавливает резервную копию.Не уверен, в чем проблема

Файл Restorebackup.py

import pyodbc 
import os
#######################################################################################################################      
def restore_backup(selectedChoiceServer, selectedChoiceDatabase, selectedChoiceSchema, filePath):
    try:   
        driver= '{SQL Server}'        
        selectedChoiceServer="localhost"        
        db_environment= 'master'        
        username= 'sqlserverloginforlocalhost'        
        password='yourpassword'
        connectionString = (('DRIVER='+driver+';PORT=1433;SERVER='+selectedChoiceServer+';PORT=1443;DATABASE='+ db_environment +';UID='+username+';PWD='+ password)) 
        db_connection = pyodbc.connect(connectionString, autocommit=True)
        cursor = db_connection.cursor()      
        cursor.execute("""RESTORE FILELISTONLY FROM DISK = '"""+filePath+"""'""")
        dataset = cursor.fetchall()
        YourMDFLogicalName = dataset[0][0]
        YourLDFLogicalName = dataset[1][0]
        if not os.path.exists('c:/mybackup/backuptest'):
            os.mkdir('c:/mybackup/backuptest')
        db_connection = pyodbc.connect(connectionString, autocommit=True)
        sql = """  
        USE [master]
        RESTORE DATABASE [testdatabase] FROM  
        DISK = N'"""+filePath+"""' 
        WITH  FILE = 1
        ,RECOVERY
        ,  MOVE N'Service' TO N'C:/mybackup/backuptest/""" + YourMDFLogicalName + """.mdf'
        ,  MOVE N'Service_log' TO N'C:/mybackup/backuptest/""" + YourLDFLogicalName + """.ldf'
        ,  NOUNLOAD,  STATS = 5
        """ 
        cursor.execute(sql)
        db_connection.autocommit = False
        return 1
    except Exception as e:
        print('Some Error Occured, so backup was not restored')
        print('Error is :' + str(e))
        return str(e)
#######################################################################################################################      

Файл tool.py

from tkinter import messagebox 
from tkinter import filedialog
import unknown_support
from Restorebackup import restore_backup
import tkinter as Tk
from tkinter import *

def vp_start_gui():
    '''Starting point when module is the main routine.'''
    global val, w, root
    root = Tk() 
    top = Tool (root)
    unknown_support.init(root, top)
    root.mainloop()

def destroy_Tool():
    root.destroy()

class Tool:
    def StartButtonAction(self):
        self.Button1.config(state=DISABLED)
        selectedChoiceServer = self.Text3.get('1.0','end-1c')
        selectedChoiceDatabase = self.Text1.get('1.0','end-1c')
        selectedChoiceSchema =   self.Text2.get('1.0','end-1c')  
        root.fileName = filedialog.askopenfilename( filetypes = ( ("bak files", "*.dat_bak"),("All files","*.*") ) )
        #root.fileName = root.fileName.replace('/', '\\')
        res = restore_backup(selectedChoiceServer, selectedChoiceDatabase, selectedChoiceSchema, root.fileName)
        if res == 1:
            messagebox.showinfo("Backup is restored", "Backup is restored")
        else:
            messagebox.showinfo("Error: ",res)

    def __init__(self, top=None):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        top.geometry("600x450+761+233")
        top.title("Backup Restore Tool")
        top.configure(background="#d9d9d9")
        top.configure(highlightbackground="#d9d9d9")    
        top.configure(highlightcolor="black")

        self.choice = IntVar()
        self.databaseChoice = StringVar()

        self.Label1 = Label(top)
        self.Label1.place(relx=0.32, rely=0.38, height=26, width=58)
        self.Label1.configure(background="#d9d9d9")
        self.Label1.configure(disabledforeground="#a3a3a3")
        self.Label1.configure(foreground="#000000")
        self.Label1.configure(text='''Schema''')

        self.Label2 = Label(top)
        self.Label2.place(relx=0.3, rely=0.24, height=26, width=69)
        self.Label2.configure(background="#d9d9d9")
        self.Label2.configure(disabledforeground="#a3a3a3")
        self.Label2.configure(foreground="#000000")
        self.Label2.configure(text='''Database''')

        self.Label3 = Label(top)
        self.Label3.place(relx=0.3, rely=0.10, height=26, width=69)
        self.Label3.configure(background="#d9d9d9")
        self.Label3.configure(disabledforeground="#a3a3a3")
        self.Label3.configure(foreground="#000000")
        self.Label3.configure(text='''Server''')

        self.Text1 = Text(top)
        self.Text1.place(relx=0.45, rely=0.24, relheight=0.05, relwidth=0.39)
        self.Text1.configure(background="#ffffffffffff")
        self.Text1.configure(font="TkTextFont")
        self.Text1.configure(foreground="black")
        self.Text1.configure(highlightbackground="#d9d9d9")
        self.Text1.configure(highlightcolor="black")
        self.Text1.configure(insertbackground="black")
        self.Text1.configure(selectbackground="#c4c4c4")
        self.Text1.configure(selectforeground="black")
        self.Text1.configure(width=234)
        self.Text1.configure(wrap=WORD)


        self.Text2 = Text(top)
        self.Text2.place(relx=0.45, rely=0.38, relheight=0.05, relwidth=0.39)
        self.Text2.configure(background="white")
        self.Text2.configure(font="TkTextFont")
        self.Text2.configure(foreground="black")
        self.Text2.configure(highlightbackground="#d9d9d9")
        self.Text2.configure(highlightcolor="black")
        self.Text2.configure(insertbackground="black")
        self.Text2.configure(selectbackground="#c4c4c4")
        self.Text2.configure(selectforeground="black")
        self.Text2.configure(width=234)
        self.Text2.configure(wrap=WORD)

        self.Text3 = Text(top)
        self.Text3.place(relx=0.45, rely=0.10, relheight=0.05, relwidth=0.39)
        self.Text3.configure(background="white")
        self.Text3.configure(font="TkTextFont")
        self.Text3.configure(foreground="black")
        self.Text3.configure(highlightbackground="#d9d9d9")
        self.Text3.configure(highlightcolor="black")
        self.Text3.configure(insertbackground="black")
        self.Text3.configure(selectbackground="#c4c4c4")
        self.Text3.configure(selectforeground="black")
        self.Text3.configure(width=234)
        self.Text3.configure(wrap=WORD)


        self.Button1 = Button(top)
        self.Button1.place(relx=0.4, rely=0.58, height=33, width=186)
        self.Button1.configure(activebackground="#d9d9d9")
        self.Button1.configure(activeforeground="#000000")
        self.Button1.configure(background="#d9d9d9")
        self.Button1.configure(disabledforeground="#a3a3a3")
        self.Button1.configure(foreground="#000000")
        self.Button1.configure(highlightbackground="#d9d9d9")
        self.Button1.configure(highlightcolor="black")
        self.Button1.configure(pady="0")
        self.Button1.configure(text='''Start''')
        self.Button1.configure(width=186)
        self.Button1.configure(command = self.StartButtonAction)


        self.Button2 = Button(top)
        self.Button2.place(relx=0.4, rely=0.68, height=33, width=186)
        self.Button2.configure(activebackground="#d9d9d9")
        self.Button2.configure(activeforeground="#000000")
        self.Button2.configure(background="#d9d9d9")
        self.Button2.configure(disabledforeground="#a3a3a3")
        self.Button2.configure(foreground="#000000")
        self.Button2.configure(highlightbackground="#d9d9d9")
        self.Button2.configure(highlightcolor="black")
        self.Button2.configure(pady="0")
        self.Button2.configure(text='''Quit''')
        self.Button2.configure(width=186)
        self.Button2.configure(command = destroy_Tool)


if __name__ == '__main__':
    vp_start_gui()
...