1

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

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]

4

2 回答 2

1

它永远不会进入 else 来插入数据,因为您的 select 语句没有被过滤。这个说法:

Select policeid, nric from PoliceAccount

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

Select policeid, nric from PoliceAccount where policeid = @policeid

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

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

最后,在插入语句上使用相同的参数化语法,它不会受到 SQL 注入的影响。

于 2013-07-29T02:42:05.390 回答
0

解决方案所说的是正确的。还要cmd.CommandType = CommandType.Text;在你的代码之前添加cmd.ExecuteNonQuery();

我也认为你应该在.aspx这里添加Response.Redirect("AdminAddAccount.aspx");

于 2013-07-29T02:51:19.477 回答