检查用户名是否存在于数据库中

时间:2014-07-04 11:41:43

标签: c# sql sql-server-express

在c#中执行此用户名检查,如果给出相同的名称,它总是输入,它从不显示检查,plz告诉为什么?

SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Ro;Integrated Security=True");
        con.Open();
        SqlCommand cmd = new SqlCommand("select Name from [Machine]", con);
        SqlDataReader rdr = cmd.ExecuteReader();
        while(rdr.Read())
        {
            query=rdr.GetString(0);
            if (query == textBox1.Text)
            {
                System.Windows.Forms.MessageBox.Show("MachineName Already exists!!!");
            }
            else
            {
                this.db.Datastore("INSERT INTO [Roamani].[dbo].[Machine] ([Name],[Type],[AETitle],[IPAddress],[Port]) VALUES('" + textBox1.Text + "','" + comboBox1.SelectionBoxItem + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "')");
                this.Hide();
                m.Show();
                return;
            }
            //return;
        }          

2 个答案:

答案 0 :(得分:3)

根据您的问题,您正在从数据库中选择所有用户并逐个比较输入的新用户名,因此可能会导致性能问题。

你可以尝试这样:

SqlConnection con = new SqlConnection("Your ConnectionString");
con.Open();

SqlCommand cmd = new SqlCommand("select * from [login] where UserName=@Name",con);
cmd.Parameters.AddWithValue("@Name", txtUsername.Text);
SqlDataReader dr = cmd.ExecuteReader();

if (dr.HasRows)
{
   // "UserName Already Taken";
 }
else
{
  //"UserName Available";
}

答案 1 :(得分:0)

public bool CheckAlredyExistProd(string catid)
{
    try
    {
        SqlConnection con = new SqlConnection(connection_string);
        con.Open();
        SqlCommand command = new SqlCommand("SELECT * FROM tblMyCart WHERE Product_Category='" + catid + "'");
        command.Connection = con;
        SqlDataReader red = command.ExecuteReader();
        if (red.HasRows)
        {
            return false;
        }
        else
            return true;
    }
    catch
    {
        throw;
    }       
}