string connectionString1 = (@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|Database1.mdf;Database=Database1;Integrated Security=True; User Instance=True");
SqlConnection cn = new SqlConnection(connectionString1);
cn.Open();
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = @"BACKUP DATABASE Database1 TO DISK = 'C:\SRI2Works.bak'";
cmd.CommandType = CommandType.Text;
cmd.Connection = cn;
reader = cmd.ExecuteReader();
cn.Close();
MessageBox.Show("Database Backup Successfull.");
恢復
string connectionString1 = (@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|Database1.mdf;Database=Database1;Integrated Security=True; User Instance=True");
SqlConnection cn = new SqlConnection(connectionString1);
cn.Open();
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = @"use master; RESTORE DATABASE Database1 FROM DISK = 'C:\SRI2Works.bak'";
cmd.CommandText = "DBCC CHECKDB ('Database1')";
cmd.CommandType = CommandType.Text;
cmd.Connection = cn;
reader = cmd.ExecuteReader();
cn.Close();
MessageBox.Show("Database Restored Successfull.");
這段代碼成功運行,但不進行任何更改。
您是如何驗證代碼確實被執行的?消息框是否觸發? – usr 2013-04-06 15:29:53
文件'C:\ SRI2Works.bak'實際寫入了嗎?而且,實際上,您的恢復命令僅執行'DBCC CHECKDB('Database1')',它取代了上面一行中設置的'CommandText'。 – 2013-04-06 15:34:50
@ThomasGerstendörfer好抓! OP應該使用SQL事件探查器來驗證預期的命令是否被實際發送。 – usr 2013-04-06 15:41:21