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

本文关键字:数据库 存在 是否 用户 检查 | 更新日期: 2023-09-27 18:11:22

在c#中做这个用户名检查,它总是输入相同的名字,它从不显示检查,请告诉为什么?

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

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

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

你可以这样试试:

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