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;
}
}
请此代码抛出此错误,
类型' System.Data.SqlClient.SqlException'未处理的异常发生在WindowsFormsApplication1.exe
中附加信息:必须声明标量变量" @ PATH"。
关键字'附近有'的语法不正确。如果此语句是公用表表达式,xmlnamespaces子句或更改跟踪上下文子句,则必须以分号结束前一个语句。
请问这段代码有什么错误?
答案 0 :(得分:0)
在定义主查询字符串后,应添加参数。
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;
}
答案 1 :(得分:0)
我认为您的代码存在一些混淆。在声明它之前使用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 " +
不完整(以+结尾)
第三我建议你在里面使用SqlConnection来确保它总是处理
using (SqlConnection connection = new SqlConnection(connectionString))
{}