備份
private void BackupDB(string dbName, string saveAt) { using (SqlConnection conn = new SqlConnection(CONN_STR)) { conn.Open(); SqlCommand cmd = new SqlCommand(" BACKUP DATABASE @DBName TO DISK = @PATH WITH STATS = 5", conn); cmd.Parameters.AddWithValue("@DBName", dbName); cmd.Parameters.AddWithValue("@PATH", saveAt); cmd.CommandTimeout = 86400000; cmd.ExecuteNonQuery(); } }
還原
public void RestoreDB(string dbName, string loadBakFilePath) { using (SqlConnection conn = new SqlConnection(CONN_STR)) { SqlConnectionStringBuilder connStrBuilder = new SqlConnectionStringBuilder(CONN_STR); connStrBuilder.InitialCatalog = "master"; conn.ConnectionString = connStrBuilder.ConnectionString; conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.CommandText = "ALTER DATABASE " + dbName + " SET Single_User WITH Rollback Immediate; RESTORE DATABASE " + dbName + " FROM DISK = @PATH WITH REPLACE; ALTER DATABASE " + dbName + " SET Multi_User;"; cmd.CommandTimeout = 86400000; cmd.Parameters.AddWithValue("@DBName", dbName); cmd.Parameters.AddWithValue("@PATH", loadBakFilePath); cmd.Connection = conn; cmd.ExecuteNonQuery(); } }
ref:CaveDweller
沒有留言:
張貼留言