检查数据库中是否存在数据

时间:2013-05-12 14:13:01

标签: c# .net

我正在使用c#创建一个登录系统。我想检查用户输入的用户名是否已经是数据库的一部分。这是连接到数据适配器的代码,然后在从复选框中获取数据后更新此代码。

NorthwindDataSetTableAdapters.CustomersTableAdapter north = new NorthwindDataSetTableAdapters.CustomersTableAdapter();
NorthwindDataSet.CustomersDataTable northtable = north.GetData();


NorthwindDataSet northwindDataSet1 = new NorthwindDataSet();
NorthwindDataSet.CustomersRow newCustomersRow =
northwindDataSet1.Customers.NewCustomersRow();

newCustomersRow.Username = TextBox1.Text.ToString();
newCustomersRow.Password = TextBox2.Text.ToString() ;
newCustomersRow.FirstName = TextBox3.Text.ToString();
newCustomersRow.Surname = TextBox4.Text.ToString();

northwindDataSet1.Customers.Rows.Add(newCustomersRow);

north.Update(northwindDataSet1.Customers);
northwindDataSet1.Customers.AcceptChanges();

if (Page.IsValid)
 Response.Redirect("thankyou.aspx"); 

检查Username字段中重复数据的最佳方法是什么?

3 个答案:

答案 0 :(得分:3)

叫我疯了,但我只是做一些事情(使用“dapper”)

string username = ...
int existingId = connection.Query<int?>(
    @"select top 1 Id from Users where UserName = @username",
     new { username }).FirstOrDefault();
 if(existingId.HasValue) {
       // not available - do something
 }      

请注意,此处存在竞争条件,因此您仍应对列本身具有唯一约束。您可能还想了解区分大小写的事情:“Fred”与“fred”的用户名相同吗?

答案 1 :(得分:0)

为什么不将表列标记为主键或唯一?然后在try {} catcht {}语句中处理异常。

答案 2 :(得分:0)

您是否尝试过使用DataTable.Select?类似的东西:

var UserFound = NorthTable.Select("UserName = '" + TextBox1.Text + "'");
if(UserFound.Length != 0)
{
    // do something...
}