Ramji Ramji - 4 years ago 131
SQL Question

[Solved]Check username exists in database or not

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

Answer Source

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";
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download