下面是书上的例子,是增加用户的代码,在这个代码中我看不到关于验证用户重复注册的处理,可是重复注册的话还是有提示的,数据库里的表我也看了,并不是用用户名的列做为主键的,它是怎么做到,请大家看看,有答案马上结帖给分
private void InsertUser()
{
if (Page.IsValid)
{
// Save new user to the database
SqlConnection con;
string sql;
SqlCommand cmd;
StringBuilder sb = new StringBuilder();
ArrayList values = new ArrayList(); sb.Append("INSERT INTO [User] ");
sb.Append("(UserID, Login, Password, FirstName, LastName,");
sb.Append(" PhoneNumber, Email, IsAdministrator, Address,");
sb.Append(" CellNumber, DateOfBirth) ");
sb.Append("VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', "); // Optional values without quotes as they can be the Null value.
sb.Append("{8}, {9}, {10})"); // Add required values to replace
values.Add(Guid.NewGuid().ToString());
values.Add(txtLogin.Text);
values.Add(txtPwd.Text);
values.Add(txtFName.Text);
values.Add(txtLName.Text);
values.Add(txtPhone.Text);
values.Add(txtEmail.Text);
values.Add(0); // Add the optional values or Null
if (txtAddress.Text != string.Empty)
values.Add("'" + txtAddress.Text + "'");
else 
values.Add("Null"); if (txtMobile.Text != string.Empty)
values.Add("'" + txtMobile.Text + "'");
else 
values.Add("Null"); if (txtBirth.Text != string.Empty)
values.Add("'" + txtBirth.Text + "'");
else
values.Add("Null"); // Format the string with the array of values
sql = String.Format(sb.ToString(), values.ToArray()); // Connect and execute the query
con = new SqlConnection("data source=(local)\\NetSdk;initial catalog=FriendsData;user id=sa");
cmd = new SqlCommand(sql, con);
con.Open(); bool doredirect = true; try
{
cmd.ExecuteNonQuery();
}
catch
{
doredirect = false;
this.lblMessage.Visible = true;
this.lblMessage.Text = "Insert couldn't be performed. User name may be already taken.";
}
finally
{
con.Close();
} if (doredirect)
Response.Redirect("Login.aspx");
}
else
lblMessage.Text = "Fix the following errors and retry:";
}

解决方案 »

  1.   

    try
    {
    cmd.ExecuteNonQuery();
    }
    catch
    {
    doredirect = false;
    this.lblMessage.Visible = true;
    this.lblMessage.Text = "Insert couldn't be performed. User name may be already taken.";
    }
    finally
    {
    con.Close();
    }是这段代码起的作用,错误处理而已
      

  2.   

    这应该是与数据库表设计有关,它可能是把用户名设置为Unique属性,当插入相同用户名是便会抛出异常,捕获此异常,显示.
      

  3.   

    try
    {
    }
    catch
    {
    }
    捕获错误,然后提示用户存在,最好是看一下数据库的设计,应该是数据库的表不允许,插入重复记录,所以执行command的时候出错,所以你就不能插入重复记录了!!
      

  4.   

    TO:sweetsoft() 是userid是主键吗?
    是的,是用USERID作为主键的,
    另外,这里根据Login来判断是否有重复的,在表上也没有做任何的设计,我就是不明白这段代码任何来判断Login是否有重复
      

  5.   

    肯定有数据库表的某个字段设为unique,这样便可利用数据库进行检查,如有重复,则抛出异常
      

  6.   

    to:wl_weiliang(麦克老狼) 
    在数据库中的表的主键都是用GUID,会不会是这个起的作用?
      

  7.   

    如果不是用用户名作为主键的,那一定是用PKId作为主键的,PKId是一个int型的自动累加1的主键Id字段
      

  8.   

    找到了,在表中有一给唯一索引,列Login创建了unique,多谢 wl_weiliang(麦克老狼) 和大家,揭贴