Check username exists in database or not

荒凉一梦 提交于 2019-12-12 07:02:01

问题


doing this username checking in c#,it always enter if same name given,It never shows checking,plz tell why?

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;
        }          

回答1:


As per your question, you are selecting all users from database and comparing one by one with the new username be entered thus may cause performance issues.

You Can Try Like This:

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";
}



回答2:


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;
    }       
}


来源:https://stackoverflow.com/questions/24573481/check-username-exists-in-database-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!