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