【发布时间】:2016-08-12 06:08:40
【问题描述】:
我目前有一个 asp.net 网站。但是我注意到在我的注册页面中,用户可以使用相同的用户名进行多次注册。因此,我想知道是否有办法防止用户使用相同的用户名多次注册。
我确实知道我可以在我的数据库中设置一个列来拥有一个主键...但是如果我想让多个列拥有主键我该怎么办?
这是我的插入代码....
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 数据库中,但是输入的数据可以针对不同用户的用户名和电子邮件字段重复,我不希望这种情况发生。
【问题讨论】:
-
至少给数据库添加一些约束,这样你的代码在尝试插入重复项时会引发异常。