2014-02-06 129 views
0

首先,我注册到我的网站上,然后我可以使用用户名和密码加入私人组。问题是,如果我试图插入已加入的组中,表中会出现重复的记录。所以我有一个成员表(MemberId-PK,用户名等),一个分配组表(MemberId-FK),(GroupId-FK)和一个组(GroupId-PK),名称,密码,体育)表。避免表中的重复记录asp.net

这里是我的代码:

protected void Button1_Click(object sender, EventArgs e) 
    { 

     SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Tom\Documents\BIS\4th Year\FYP\FYP\Back-up\test2\FitnessForYou V1-08.01\FitnessForYou\FitnessForYou\App_Data\MembersData.mdf;Integrated Security=True"); 

     con.Open(); 

     SqlCommand cmd2 = new SqlCommand("select COUNT(*)FROM Groups WHERE GroupName='" + txtGroupName.Text + "' and Password='" + txtPassword.Text + "'"); 




     cmd2.Connection = con; 




     int OBJ = Convert.ToInt32(cmd2.ExecuteScalar()); 
     if (OBJ > 0) 
     { 

      con.Close(); 
      con.Open(); 

      cmd2.CommandText = "Insert into AssignGroups(MemberId,GroupId) Select Members.MemberId, Groups.GroupId From Members, Groups Where Members.Username= '" + lblRegistered.Text + "' And Groups.GroupName= '" + txtGroupName.Text + "'"; 



      Session["GroupName"] = txtGroupName.Text; 




      cmd2.ExecuteNonQuery(); 
      cmd2.Clone(); 
      Response.Redirect("GroupMembers.aspx"); 
     } 
     else 
     { 
      lblError.Text = "Invalid username or password"; 
      this.lblError.ForeColor = Color.Red; 
     } 
     con.Close(); 
    } 

此代码插入你的记录到tabeo是否有重复或没有。我如何能够检查数据库,看看你是否已经是成员,因此给他们一个提示,而不必再次插入记录。

谢谢!

+3

您有一个SQL注入漏洞。 – SLaks

+3

**不要以纯文本格式存储密码!** – SLaks

+2

安全性很难**。不要重新发明轮子。您应该使用现有的,经过验证的认证系统。 – SLaks

回答

1

尝试添加cmd2.Connection = con;在执行命令之前。 上述代码中命令和连接之间没有关系。

+0

感谢您的回复。我已经使用cmd2.Connection = con编辑了我的答案。我怎么能够在插入之前检查记录是否已经存在? – user3249809

+0

您可以检查(OBJ == 0){插入代码} else {记录已存在的代码}。我认为你的代码似乎是正确的。只需用OBJ == 0改变OBJ> 0。 –

+0

改变之后,它确实停止了重复,但当没有重复时它也停止合法插入。这个阶段非常接近。你是否看到我可能添加的任何其他解决方法? – user3249809

0

我不是一个SQL人,但这里是一个查询,你可能想运行检查一个成员是否已分配到一个组。

Select Count(*) from AssignGroups where 
    MemberId IN (Select MemberID from Members where Username='username') 
    And GroupId IN (Select GroupID from Groups where GroupName='YourGroupName') 

如果它返回一个正值,则该成员已被分配给该组,因此不做任何事情。 否则,成员未分配,您可以运行插入查询。