无法在数据库中插入和检查类似数据

时间:2013-07-29 02:13:29

标签: c# asp.net

我正在尝试将帐户插入数据库。在下面添加我的语法之前,我将简要解释一下我的代码的作用。通常,我正在检查特定文本框是否为空。如果不是,它将尝试将数据插入数据库。但是,如果数据库包含的数据类似于文本框中的类型,则它们将分别提示不同的错误。不幸的是,对我来说,我甚至无法插入任何数据,也没有错误显示文本框和数据库中的数据是相同的

protected void btnAdd_Click(object sender, EventArgs e)
    {

        if (tbpid.Text.Equals(""))
        {
            lbmsg.Text = "Please generate a police ID for this account";
        }
        else if (tbfullname.Text.Equals(""))
        {
            lbmsg.Text = "Please type the full name of the police officer";
        }
        else if (tbnric.Text.Equals(""))
        {
            lbmsg.Text = "Please enter the NRIC of the police officer";
        }
        else if (ddllocation.SelectedValue.Equals("Select Location"))
        {
            lbmsg.Text = "Please select the location of the policepost he will be posted to";
        }
        else { 

        SqlConnection con = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI");
        con.Open();
        SqlCommand select = new SqlCommand("Select policeid, nric from PoliceAccount where policeid = @policeid", con);
        SqlDataReader dr;

select.Parameters.AddWithValue("@policeid", tbpid.Text);

        dr = select.ExecuteReader();
        if (dr.Read())
        {
            if (tbpid.Equals(dr["policeid"].ToString()))
            {

                lbmsg.Text = "Police ID already exists. Please generate another new Police ID";

            }
            else if (tbnric.Equals(dr["nric"].ToString()))
            {
                lbmsg.Text = "NRIC already exists. Please ensure the NRIC is correct";
            }

        }

        else
        {

            SqlConnection conn = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI");
            conn.Open();
            SqlCommand cmd = new SqlCommand("insert into PoliceAccount(policeid, password, nric, fullname, postedto)  values('" + tbpid.Text.Trim() + "','" + tbpid.Text.Trim() + "','" + tbnric.Text.Trim() + "','" + tbfullname.Text.Trim() + "', '" + ddllocation.SelectedValue + "')", conn);
            cmd.ExecuteNonQuery();
            conn.Close();

            Response.Redirect("AdminAddAccount");

        }

        }

    }

请参阅此[主题以获取正确答案] [1]

2 个答案:

答案 0 :(得分:1)

它永远不会进入else,插入数据,因为你的select语句没有被过滤。这句话:

Select policeid, nric from PoliceAccount

将返回该表中的所有行。但是,你真正想要的是:

Select policeid, nric from PoliceAccount where policeid = @policeid

然后,在执行阅读器之前,添加以下代码行:

select.Parameters.AddWithValue("@policeid", tbpid.Text);

最后,在insert语句中使用相同的参数化语法,从SQL注入中是安全的。

答案 1 :(得分:0)

解决方案所说的是对的。另请在cmd.CommandType = CommandType.Text;之前的代码中添加cmd.ExecuteNonQuery();

此外,我认为您应在.aspx

添加Response.Redirect("AdminAddAccount.aspx");