【发布时间】:2016-12-21 03:58:51
【问题描述】:
我的代码有问题:
public partial class DeleteStaff : System.Web.UI.Page
{
string username = null;
SqlConnection conn = null;
SqlCommand cmd = null;
string connectionString = null;
protected void Page_Load(object sender, EventArgs e)
{
// if loading the page for the first time
if (!IsPostBack)
{
// Check that there is an id passed in with the QueryString
if (Request.Params["username"] != null)
{
// retrieve the id
username = Convert.ToString(Request.Params["username"]);
}
// retrieve connectionString from Web.Config file
connectionString = ConfigurationManager.ConnectionStrings["LMSCS"].ConnectionString;
// create connection with database specified in the connectionString
conn = new SqlConnection(connectionString);
// prepare sql statement
string sql = "DELETE FROM Staff WHERE Username=@username";
try
{
// create SqlCommand object with sql statement and connection
cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@username", username);
// Open database connection
conn.Open();
// Execute SqlCommand
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
lblOutput.Text = "Record deleted successfully.";
}
else
{
lblOutput.Text = "Record cannot be deleted.";
}
}
catch (Exception ex)
{
lblOutput.Text = "Error Message: " + ex.Message;
}
finally
{
if (conn != null)
conn.Close();
}
}
}
}
一旦我按下删除,但对于特定项目,我会收到此错误:
参数化查询“(@username nvarchar(4000))DELETE FROM Staff WHERE Username=@user”需要参数“@username”,但未提供该参数。
【问题讨论】:
-
您确定此代码会产生该错误吗?查询文本包含一个名为
@username的参数占位符,但错误显示带有占位符@user的不同查询
标签: c# sql sql-server visual-studio