Thứ Bảy, 6 tháng 6, 2020

SQL Server Database Backup and Restore in C#

Đăng Bởi: Admin - tháng 6 06, 2020 - 0 Bình Luận






https://www.codeproject.com/Tips/873677/SQL-Server-Database-Backup-and-Restore-in-Csharp

https://foxlearn.com/article/restore-sql-database-backup-in-csharp-106.html

https://www.youtube.com/watch?v=1o3e2NV7ovE

//code for backup browse button FolderBrowserDialog fbd = new FolderBrowserDialog(); if (fbd.ShowDialog() == DialogResult.OK) { BackupTextBox.Text = fbd.SelectedPath; BrowseBackupBtn.Enabled = true; } //code for backup button con.Open(); String database = con.Database.ToString(); try { if (BackupTextBox.Text == string.Empty) { // s.Speak("please enter the valid backup file location"); MessageBox.Show("please enter the backup file location"); } else { string q = "BACKUP DATABASE [" + database + "] TO DISK='" + BackupTextBox.Text + "\\" + "Database" + "-" + DateTime.Now.ToString("yyyy-MM-dd--HH-mm-ss") + ".bak'"; SqlCommand scmd = new SqlCommand(q, con); scmd.ExecuteNonQuery(); // s.Speak("Backup taken successfully"); MessageBox.Show("Backup taken successfully", "Backup successs", MessageBoxButtons.OK, MessageBoxIcon.Information); button2.Enabled = false; } //code for restore browse button OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "SQL SERVER database backup files|*.bak"; ofd.Title = "Database Restore"; if (ofd.ShowDialog() == DialogResult.OK) { RestoreTextBox.Text = ofd.FileName; RestoreBtn.Enabled = true; } //code for the restore button con.Open(); String database = con.Database.ToString(); try { string sql1 = string.Format("ALTER DATABASE [" + database + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE"); SqlCommand cmd1 = new SqlCommand(sql1, con); cmd1.ExecuteNonQuery(); string sql2 = string.Format("USE MASTER RESTORE DATABASE [" + database + "] FROM DISK='" + RestoreTextBox.Text + "' WITH REPLACE;"); SqlCommand cmd2 = new SqlCommand(sql2, con); cmd2.ExecuteNonQuery(); string sql3 = string.Format("ALTER DATABASE [" + database + "] SET MULTI_USER"); SqlCommand cmd3 = new SqlCommand(sql3, con); cmd3.ExecuteNonQuery(); // s.Speak("Database Restored successfully"); MessageBox.Show("Database Restored successfully", "Restore Database successs", MessageBoxButtons.OK, MessageBoxIcon.Information); button2.Enabled = false; } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { con.Close(); }













Phản Hồi Độc Giả

Một số lưu ý khi bình luận

Mọi bình luận sai nội quy sẽ bị xóa mà không cần báo trước (xem nội quy)

Bấm Thông báo cho tôi bên dưới khung bình luận để nhận thông báo khi admin trả lời

Để bình luận một đoạn code, hãy mã hóa code trước nhé