数据库还原中出错
本文关键字:出错 还原 数据库 | 更新日期: 2023-09-27 18:34:05
private void restoreBtn_Click(object sender, EventArgs e)
{
try
{
if (databaseCmbBox.Text.CompareTo("") == 0)
{
MessageBox.Show("Please Select A Database");
return;
}
con = new SqlConnection(connectionString);
con.Open();
sql = "ALTER DATABASE " + databaseCmbBox.Text +" SET Single_User WITH Rollback Immediate ; RESTORE DATABASE " +
databaseCmbBox.Text + " FROM DISK = @PATH WITH REPLACE ; ALTER DATABASE " + databaseCmbBox.Text + " SET Multi_User ;";
comm.Parameters.AddWithValue("@PATH", databaseRestorePath.Text);
comm.CommandTimeout = 86400000;
//sql = "Alter Database "+databaseCmbBox.Text+" Set SINGLE_USER WITH ROLLBACK IMMEDIATE";
//sql += "RESTORE Database " + databaseCmbBox.Text + " FROM DISK = '" + databaseRestorePath.Text + "' WITH REPLACE";
comm = new SqlCommand(sql, con);
comm.ExecuteNonQuery();
con.Close();
con.Dispose();
MessageBox.Show("Database Succesfully Restored");
}
catch (Exception)
{
throw;
}
}
请此代码抛出此错误,
WindowsFormsApplication1 中发生了类型为"System.Data.SqlClient.SqlException"的未处理异常.exe
其他信息:必须声明标量变量"@PATH"。
关键字"with"附近的语法不正确。如果此语句是公用表表达式、xmlnamespaces 子句或更改跟踪上下文子句,则前面的语句必须以分号结尾。
请问这个代码有什么错误?
应在定义主查询字符串后添加参数。
private void restoreBtn_Click(object sender, EventArgs e)
{
try
{
if (databaseCmbBox.Text.CompareTo("") == 0)
{
MessageBox.Show("Please Select A Database");
return;
}
con = new SqlConnection(connectionString);
con.Open();
sql = "ALTER DATABASE " + databaseCmbBox.Text +" SET Single_User WITH Rollback Immediate ; RESTORE DATABASE " +
databaseCmbBox.Text + " FROM DISK = @PATH WITH REPLACE ; ALTER DATABASE " + databaseCmbBox.Text + " SET Multi_User ;";
comm.CommandTimeout = 86400000;
//sql = "Alter Database "+databaseCmbBox.Text+" Set SINGLE_USER WITH ROLLBACK IMMEDIATE";
//sql += "RESTORE Database " + databaseCmbBox.Text + " FROM DISK = '" + databaseRestorePath.Text + "' WITH REPLACE";
comm = new SqlCommand(sql, con);
comm.Parameters.AddWithValue("@PATH", databaseRestorePath.Text);
comm.ExecuteNonQuery();
con.Close();
con.Dispose();
MessageBox.Show("Database Succesfully Restored");
}
catch (Exception)
{
throw;
}
我认为您的代码中存在一些混乱。在声明变量之前comm
使用它(也许这也是一个错误),但是第一
comm = new SqlCommand(sql, con);
然后
comm.Parameters.AddWithValue("@PATH", databaseRestorePath.Text);
comm.CommandTimeout = 86400000;
第二个显示完整的 sqlcommand,因为
sql = "ALTER DATABASE " + databaseCmbBox.Text +" SET Single_User WITH Rollback Immediate ; RESTORE DATABASE " +
不完整(以 + 结尾)
第三,我建议您在 using 语句中使用 SqlConnection 以确保它始终被处理
using (SqlConnection connection = new SqlConnection(connectionString))
{}