我目前有一个asp.net网站。但是我注意到,在我的注册页面中,用户可以使用相同的用户名进行多次注册。因此,我想知道是否有办法阻止用户使用相同的用户名多次注册。如何防止重复的数据值出现在MySQL数据库中
我知道我可以在我的数据库中设置一个列来创建主键......但是,如果我想让多个列具有主键,我该怎么办?
这是我的插入代码....
MySqlCommand command = mcon.CreateCommand();
mcon.Open();
command.CommandText = "insert into pointofcontact (FirstName, LastName, EmailAddress, ContactNumber, BackupContactNumber, Address, Gender, Username, Password, Status, ProfilePic) values(?firstname, ?lastname, ?emailaddress, ?contactnumber, ?backupcontactnumber, ?address, ?gender, ?username, ?password, ?status, ?image)";
command.Parameters.AddWithValue("?firstname", firstname);
command.Parameters.AddWithValue("?lastname", lastname);
command.Parameters.AddWithValue("?emailaddress", email);
command.Parameters.AddWithValue("?contactnumber", mobileNumber);
command.Parameters.AddWithValue("?backupcontactnumber", backupNumber);
command.Parameters.AddWithValue("?address", homeAddress);
command.Parameters.AddWithValue("?gender", gender);
command.Parameters.AddWithValue("?username", username);
command.Parameters.AddWithValue("?password", password);
command.Parameters.AddWithValue("?status", status);
command.Parameters.AddWithValue("?image", imageName);
command.ExecuteNonQuery();
mcon.Close();
MySqlDataReader reader = null;
mcon.Open();
MySqlCommand command2 = mcon.CreateCommand();
command2.CommandText = "select * from pointofcontact where Username = ?username";
command2.Parameters.AddWithValue("?username", tbUsername.Text);
reader = command2.ExecuteReader();
if (reader != null && reader.HasRows)
{
lblValidate.Text = "Username already exists.";
}
Response.Redirect("IndexAfterLogin1.aspx");
的数据表明,用户输入能够被插入到我的MySQL数据库,但输入的数据能够被重复的用户名和电子邮件领域为不同的用户,我不希望这种情况发生。
的可能的复制[?我如何指定MySQL中多列唯一约束](http://stackoverflow.com/questions/635937/how-do-i-specify-unique-constraint-for-multiple-columns-in-mysql) –
至少为数据库添加一些约束,所以当你尝试插入重复时,你的代码会引发异常。 –