我在使用if else語句的程序中檢查了這個錯誤。我有兩件事要檢查。他們是跳過一個錯誤檢查if if else語句
PoliceID(PK)
身份證
下面檢查語句如果文本框有PoliceID和身份證號碼相同的值在數據庫中。
if (tbpid.Text.Equals(dr["policeid"].ToString().Trim()) && (tbnric.Text.Equals(dr["nric"].ToString().Trim())))
{
lbmsg.Text = "This police account has already exist. Please verify the details again.";
}
如果文本框(police id)與數據庫中的值相同,它們會給出另一個不同的錯誤。
if (tbpid.Text.Equals(dr["policeid"].ToString()))
{
lbmsg.Text = "This police ID has already exists. Please generate another Police ID";
}
如果文本框(身份證)具有相同的值在數據庫中,他們會給另一個錯誤
if (tbnric.Text.Equals(dr["nric"].ToString()))
{
lbmsg.Text ="This NRIC has already exist. Please ensure that the NRIC is correct";
}
如果我是所有錯誤校驗信息結合在一起會是這樣的。
protected void btnAdd_Click(object sender, EventArgs e)
{
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.Text.Equals(dr["policeid"].ToString().Trim()) && (tbnric.Text.Equals(dr["nric"].ToString().Trim())))
{
lbmsg.Text = "This police account has already exist. Please verify the details again.";
}
else if (tbpid.Text.Equals(dr["policeid"].ToString()))
{
lbmsg.Text = "This police ID has already exists. Please generate another Police ID";
}
else if (tbnric.Text.Equals(dr["nric"].ToString()))
{
lbmsg.Text ="This NRIC has already exist. Please ensure that 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();
lbmsg.Text = "Congratulations. The police account of ID " + tbpid.Text + " has been successfully added. You may edit the profile via the edit profile tab above";
tbpid.Text = "";
tbnric.Text = "";
tbfullname.Text = "";
ddllocation.SelectedValue = "Select Location";
}
//ConfirmButtonExtender2.ConfirmText = "Are you sure you want to add this Police Account " + tbpid.Text + " ?";
}
}
但是,這裏的問題是錯誤檢查消息的前兩個語句設法工作。不幸的是,這個NRIC不起作用。例如,如果我要輸入不同的policeID但是相同的NRIC,數據仍然被插入到數據庫中,這意味着它完全忽略了上面的NRIC錯誤檢查。我一直在看它幾個小時,我還沒有找到問題。如果有人能指導我這一點,將不勝感激。
要添加的,在我的數據庫,我已經把我的主鍵爲policeID而身份證只是在我的數據庫
問候一個常規數據列。
你讓我難過。你的代碼對於sql注入非常脆弱,你應該考慮修復它。 – Peter
我知道所謂的SQL注入,但我目前主要關心的不是那個。我仍然試圖做一個只能由我使用的簡單應用程序。至於安全方面,完成我的項目後,我一定會考慮。不過謝謝你的關心。 –
@TeoChuenWeiBryan閱讀下面的答案我確定它會幫助你? –