System.Data.SqlClient.SqlException:'违反主键约束

Posted

技术标签:

【中文标题】System.Data.SqlClient.SqlException:\'违反主键约束【英文标题】:System.Data.SqlClient.SqlException: 'Violation of PRIMARY KEY constraintSystem.Data.SqlClient.SqlException:'违反主键约束 【发布时间】:2022-01-06 12:22:48 【问题描述】:
private void btnRegister_Click(object sender, EventArgs e)

    SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=LoginInfo;Persist Security Info=True;User ID=MJ;Password=12345");
    con.Open();

    if (tbRegisterConfirmPassword.Text != string.Empty || tbRegisterPassword.Text != string.Empty || tbRegisterUser.Text != string.Empty)
    
        SqlConnection connection = new SqlConnection();
        SqlCommand command = new SqlCommand();
        SqlDataReader dr;
           
        if (tbRegisterPassword.Text == tbRegisterConfirmPassword.Text)
        
            command = new SqlCommand("select * from tbl_acc where username = '" + tbRegisterUser + "'", con);
            dr = command.ExecuteReader();

            if (dr.Read())
            
                dr.Close();
                lbRegister.Text = "Username Already Taken";
                lbRegister.ForeColor = Color.Red;
            
            else
            
                dr.Close();

                command = new SqlCommand("insert into tbl_acc values (@username, @password)", con);
                command.Parameters.AddWithValue("username", tbRegisterUser.Text);
                command.Parameters.AddWithValue("password", tbRegisterPassword.Text);
                command.ExecuteNonQuery();

                MessageBox.Show("Your account has now been registered", "Registration Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            
        
        else
        
            lbRegister.Text = "Password does not match";
            lbRegister.ForeColor = Color.Red;
        
    
    else
    
        lbRegister.Text = "Please fill out all the fields";
        lbRegister.ForeColor = Color.Red;
    

【问题讨论】:

SQL Injection alert - 您应该将您的 SQL 语句连接在一起 - 使用 参数化查询 来避免 SQL 注入 - 查看Little Bobby Tables 永远不要选择 * 永远不要以明文形式存储最终用户密码。 并且始终在您的INSERT 子句中包含一个列列表。 哦,AddWithValue is evil 【参考方案1】:

这是 EF 的样子:

private void SetRegLabel(string s)
    lbRegister.ForeColor = s == null ? Color.Black : Color.Red;
    lbRegister.Text = s;


private void btnRegister_Click(object sender, EventArgs e)

    SetRegLabel(null);

    if(tbRegisterConfirmPassword.Text != tbRegisterPassword.Text)
      SetRegLabel("Passwords don't match");

    else if (new[] tbRegisterConfirmPassword, tbRegisterPassword, tbRegisterUser.Any(tb => string.IsNullOrWhiteSpace(tb.Text))) 
      SetRegLabel("Fill in all fields");

    else if(context.Users.Any(u => u.UserName == tbRegisterUser.Text)) 
      SetRegLabel("Username taken");

    else 
      context.Users.Add(new User() 
        UserName = tbRegisterUser.Text, 
        Password = Convert.ToBase64String(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes("saaalt33"+tbRegisterPassword.Text)))
      );
      context.SaveChanges();
    

【讨论】:

以上是关于System.Data.SqlClient.SqlException:'违反主键约束的主要内容,如果未能解决你的问题,请参考以下文章