检查用户名是否存在于数据库中 [英] Check username exists in database or not

查看:39
本文介绍了检查用户名是否存在于数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

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.

你可以这样尝试:

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

这篇关于检查用户名是否存在于数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆