1

我之前尝试过发布这个并且不得不删除它,因为代码编辑器没有正确和不完整地发布它。另外,我有一个成员问我有关 SQL 注入的问题。

这是故事:

我有一个页面,用户可以在其中检查他的信息,然后再将其提交到数据库。我要做的就是在提交之前查看该主键是否存在,以避免出现服务器错误。

在我的页面加载事件中,我有以下内容:

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString);

SqlCommand oldcmd = new SqlCommand("SELECT * from dbo.registrar WHERE [MY ID] = '"+ID+"'", conn);
oldcmd.CommandType = CommandType.Text;

SqlDataAdapter da = new SqlDataAdapter(oldcmd);
DataTable dt = new DataTable();
da.Fill(dt);

if (dt.Rows.Count >= 1)
{
   lblExists.Visible = true;
   lblExists.ForeColor = System.Drawing.Color.Red;
   lblExists.Text = "Oops! Our records show that you have already signed up for this service. Please check your information or contact your administrator for further assistance.";
}

即使数据库中没有记录告诉我我做错了,标签也会触发。

4

1 回答 1

6

试试这个。

SqlCommand oldcmd = new SqlCommand("SELECT COUNT(*) from dbo.registrar WHERE [MY ID] = @id", conn);
oldcmd.Parameters.Add("@id", SqlDbType.Int);
oldcmd.Parameters["@id"].Value = ID;

if ((int)oldcms.ExecuteScalar() >= 1)
{
    lblExists.Visible = true;
    lblExists.ForeColor = System.Drawing.Color.Red;
    lblExists.Text = "Oops! Our records show that you have already signed up for this service. Please check your information or contact your administrator for further assistance.";
}
else
{
    lblExists.Visible = false;
}
于 2012-05-04T13:39:34.150 回答