问题
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