无法检测到SQL server和文本框中的相同数据,也无法提示错误
本文关键字:数据 错误 提示 检测 SQL server 文本 | 更新日期: 2023-09-27 18:25:13
我正在努力确保用户不会插入数据库中已经存在的数据。
我使用datareader从SQL服务器读取数据。
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()) && (tbnric.Text.Equals(dr["nric"].ToString())))
{
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";
}
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";
}
}
然而,尽管在数据库中已经存在的文本框中放入了相同的policeID,但没有出现错误消息"policeID已经存在",并且插入数据失败。
然而,当我键入不同的PoliceID但相同的NRIC时,错误消息没有出现,但数据插入成功。
我只是想知道,尽管有相同的策略ID,为什么我的错误消息没有出现。
更新
我已添加
.Text
进入我的ID检查,只有一条错误消息出现。
然而,当我将.Text
添加到NRIC时,发生了一些奇怪的事情。当我键入相同的ID但不同的NRIC时,主键错误出现在我的VS2012上(很明显,这是因为我在pid上添加了主键约束),这意味着它完全忽略了我的重复检查。然而,当我键入不同的ID但相同的NRIC时,信息被提交到数据库中。这完全忽略了我所做的NRIC检查。
我仍然很好奇为什么会发生这种事。
请参阅此线程以获得正确答案
在行中
if (tbpid.Equals(dr["policeid"].ToString()))
你忘了.Text
:
if (tbpid.Text.Equals(dr["policeid"].ToString()))
在检查NRIC 时也是如此
关于
然而,当我键入不同的PoliceID但相同的NRIC时,错误消息没有出现,但数据插入成功。
我假设您的表在policeid
列上有uniq约束,但在nric
上没有