我正在Asp.net(C#)中处理我的项目,我有一个文本框可以从用户那里得到一个字符串(通过单击按钮),就像我从用户那里得到的所有字符串一样-(用户名,电子邮件等),我检查输入字符串在数据库(SQL)中是否存在,如果存在,则显示错误消息。
我在文件后面的.cs代码中使用此代码:
string cn = cnTextBox.Value;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT [CN] FROM [dbo].[MyTable] WHERE CN=@CN");
cmd.Parameters.AddWithValue("@CN", cn);
cmd.Connection = con;
SqlDataReader dr = cmd.ExecuteReader();
bool theSame = false;
if (dr.HasRows())
while (dr.Read())
{
string value = dr["CN"].ToString();
if (cn == value)
theSame = true;
}
if (theSame)
errorMessage.Style["display"] = "block";
else
errorMessage.Style["display"] = "none";
if (!theSame)
// code to insert the string to a new record in the database, works fine.
您可以看到,我在WHERE
(参数化)查询中使用了SELECT
子句,以验证数据库中是否已存在该字符串。
注意:数据库中的“ CN”列的类型为varchar(50)
。
问题是(如果从未在此之前经历过,而且这并不是我第一次来这样做),如果我在数据库(在CN列中)的记录中有字符串“ xxxxx”并且输入的字符串我要插入的是“ xxxxx n ”(长度不相同)或“ xxxxn”(不相同的字符),以上检查返回此输入已经存在于数据库中,并且错误消息显示。甚至更奇怪?毕竟该字符串已插入数据库。
注意:当我使用Internet Explorer 11测试项目时,一次又一次地发生这种情况,但是当我使用其他类似Firefox的Bowser时却从未发生过。
出问题了吗?有什么建议吗? 感谢帮助!
答案 0 :(得分:2)
评论太久。您确定要查看应用程序使用的同一数据库吗?
不相关的提示
SqlConnection
,SqlCommand
和SqlDataReader
均为IDisposable
,因此每个都应放在using
块中。SqlCommand
的构造函数。dr["CN"].ToString();
更喜欢dr.GetString(0);
答案 1 :(得分:1)
修改您的值已通过。可能会添加额外的空间,使它与您所说的“ xxxx”和“ xxxxn”不同,n可能是额外的空间。