我之前尝试发布此内容并且必须删除它,因为代码编辑器没有正确且不完整地发布它。加上我有一个成员问我有关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.";
}
即使数据库中没有记录告诉我我做错了,标签也会触发。
答案 0 :(得分: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;
}