使用C#检查用户是否已存在于MySql数据库中

时间:2013-07-07 09:55:00

标签: c# mysql sql visual-studio

我有以下代码,我希望代码可以查询数据库:

 MySqlConnection connection = new MySqlConnection(Connection);
 MySqlCommand cmd;
 connection.Open();
  try
  {
    cmd = connection.CreateCommand();
    cmd.CommandText = ("INSERT INTO edata (username) VALUES ('" + this.NewUserName.Text +"') ;");
    MySqlDataReader myReader;
    myReader = cmd.ExecuteReader();
    loading.Show();
    MessageBox.Show("Your Account Has Been Created!!");
    connection.Close();
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message);
  }

如果客户端输入(NewUserName.Text)与数据库中的用户名相同,则应该有错误消息,否则将出现重复的用户名。我怎么能这样做?

我已经将连接作为字符串。

提前谢谢!!!

PS我是学习C#和MySql的学生,我很感激任何帮助和建议!

3 个答案:

答案 0 :(得分:1)

您可以在数据库的用户名字段中创建唯一约束,如果用户已存在,则会引发异常。

或者,您可以从表格中进行手动选择,并在插入之前查看是否有同名用户。

答案 1 :(得分:1)

您可以在适当的列(doc)上创建唯一索引。

CREATE UNIQUE INDEX uq_username ON edata (username);

答案 2 :(得分:1)

你使用的是会员类吗?

      MembershipCreateStatus createStatus;
        MembershipUser newUser = Membership.CreateUser(txtEmail.Text, "password", txtEmail.Text,"What was your first school?","idk", true, out createStatus);


            switch (createStatus)
        {
            case MembershipCreateStatus.Success:
           //do your actions here
            case MembershipCreateStatus.DuplicateUserName:
                CreateAccountResults.Text = "There already exists a user with this username.";
                break;

            case MembershipCreateStatus.DuplicateEmail:
                CreateAccountResults.Text = "There already exists a user with this email address.";
                break;
            case MembershipCreateStatus.InvalidEmail:
                CreateAccountResults.Text = "There email address you provided in invalid.";
                break;
            case MembershipCreateStatus.InvalidAnswer:
                CreateAccountResults.Text = "There security answer was invalid.";
                break;
            case MembershipCreateStatus.InvalidPassword:
                CreateAccountResults.Text = "The password you provided is invalid. It must be seven characters long and have at least one non-alphanumeric character.";

                break;
            default:
                CreateAccountResults.Text = "There was an unknown error; the user account was NOT created.";
                break;
        }

如果您没有使用它,那么只需创建一个读取数据库并在上面的代码之前调用它的方法:

string doesuserexist = ReadDatabase("Select Email from Patients where Email=@emailaddress").TrimEnd();
            if (checkemail != "")
            {
                CreateAccountResults.Text = "User Email Already Exists";
                return;
            }

你必须编写自己的ReadDatabase方法,但是从上面发布的代码中,你显然知道如何,只需用insert替换insert sql语句。