我正在使用带有C#的ASP.net来创建用户记录。在下面的代码中,如何设置条件以检测用户名是否已存在。
try
{
Guid newGuid = Guid.NewGuid();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string insertQuery = "insert into UsrData (Id, UserName, Email, Password, Country) values (@id, @Uname, @email, @password, @country)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("@id", newGuid);
com.Parameters.AddWithValue("@Uname", TextBoxUN.Text);
com.Parameters.AddWithValue("@email", TextBoxEmail.Text);
com.Parameters.AddWithValue("@password", TextBoxPass.Text);
com.Parameters.AddWithValue("@country", DropDownListCountry.SelectedItem.ToString());
com.ExecuteNonQuery();
Response.Redirect("login.aspx");
Response.Write("Sucessuflly registred");
conn.Close();
}
catch (Exception ex)
{
Response.Write("An unknown error " + ex.ToString());
}
答案 0 :(得分:0)
在SQL代码中放置一个存在条件:
try
{
Guid newGuid = Guid.NewGuid();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string insertQuery = @"if not exists (select * from UsrData where UserName = @Uname)
insert into UsrData (Id, UserName, Email, Password, Country) values (@id, @Uname, @email, @password, @country)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("@id", newGuid);
com.Parameters.AddWithValue("@Uname", TextBoxUN.Text);
com.Parameters.AddWithValue("@email", TextBoxEmail.Text);
com.Parameters.AddWithValue("@password", TextBoxPass.Text);
com.Parameters.AddWithValue("@country", DropDownListCountry.SelectedItem.ToString());
com.ExecuteNonQuery();
Response.Redirect("login.aspx");
Response.Write("Sucessuflly registred");
conn.Close();
}
catch (Exception ex)
{
Response.Write("An unknown error " + ex.ToString());
}
答案 1 :(得分:0)
取决于用户名检查是否应该扩展到整个表格,或者只是这一个语句(在这种情况下,Frank的回答是正确的)。
根据您使用的DBMS,您可以针对UserName列定义UNIQUE
key/constraint,这将保证唯一性。但是,在应用此约束之前,您需要确保表中当前的所有用户名都是唯一的。