0

I have the following code and I would like the code to query the database:

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

If the clients input (NewUserName.Text) is the same as the username in the database there should be an error message, otherwise there will be duplicate usernames. How can I do this?

I have already got the connection as a string.

Thank you in advance!!!

PS Im a student learning C# and MySql, I am grateful for any help and advice!

4

3 回答 3

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 sql 语句替换为 select 即可。

于 2013-07-10T03:50:37.707 回答
1

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

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

于 2013-07-07T10:02:40.240 回答
1

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

CREATE UNIQUE INDEX uq_username ON edata (username);
于 2013-07-07T10:03:28.520 回答