【问题标题】:C# SQL: Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraintsC# SQL:无法启用约束。一行或多行包含违反非空、唯一或外键约束的值
【发布时间】:2015-12-13 04:51:33
【问题描述】:

我是 C# 中的 SQL(以及一般的 SQL)的新手。

我正在制作这个简单的用户管理程序(这是一个更大的项目的一部分),您可以在其中注册一个新帐户,并在 DataGrid 中查看所有 SQL 数据库内容。

我可以添加用户(从数据库读取/写入),但由于某种原因,当我使用 DataGrid 加载 WPF 页面时,它在尝试加载时崩溃并给出错误:

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.

我试图用谷歌搜索一个答案,但我找不到答案,或者不明白我应该怎么做。

这是我的 C# 代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Shapes;
    //SQL
    using System.Configuration;
    using System.Data.SqlClient;
    using System.Data;
    namespace FMS_Csharp_GUI
    {
    /// <summary>
    /// Interaction logic for UsersBD.xaml
    /// </summary>
   public partial class UsersBD : Window
   {
        SqlConnection connection = new SqlConnection();
        string sqlConnectionString;
        public UsersBD()
    {
        InitializeComponent();
        sqlConnectionString = ConfigurationManager.ConnectionStrings["FMS_Csharp_GUI.Properties.Settings.UsersConnectionString"].ConnectionString;
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {

        FMS_Csharp_GUI.UsersDataSet usersDataSet = ((FMS_Csharp_GUI.UsersDataSet)(this.FindResource("usersDataSet")));
        // Load data into the table UsersTable. You can modify this code as needed.
        FMS_Csharp_GUI.UsersDataSetTableAdapters.UsersTableTableAdapter usersDataSetUsersTableTableAdapter = new FMS_Csharp_GUI.UsersDataSetTableAdapters.UsersTableTableAdapter();
  /*code crash in this line: */      usersDataSetUsersTableTableAdapter.Fill(usersDataSet.UsersTable); 
        System.Windows.Data.CollectionViewSource usersTableViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("usersTableViewSource")));
        usersTableViewSource.View.MoveCurrentToFirst();
    }

    private void btnAddUser_Click(object sender, RoutedEventArgs e)
    {

        string query = "INSERT INTO UsersTable VALUES (@username, @password, @IsAdmin);";

        //get input
        string username = txtUsername.Text;
        string password = txtPassword.Text;
        bool admin = chckAdmin.IsChecked == true;

        using(connection = new SqlConnection(sqlConnectionString))
        using(SqlCommand command = new SqlCommand(query,connection)) {

            connection.Open();

            command.Parameters.AddWithValue("@username", username);
            command.Parameters.AddWithValue("@password", password);
            command.Parameters.AddWithValue("@IsAdmin", admin);

            command.ExecuteScalar();
        }

    }
}
}

这是我的 SQL 数据库代码:

CREATE TABLE [dbo].[UsersTable] (
[Id]          INT        IDENTITY (1, 1) NOT NULL,
[Name]        NCHAR (15) NOT NULL,
[PasswordMD5] NCHAR (32) NOT NULL,
[IsAdmin]     BIT        DEFAULT ((0)) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);

这是我的数据库:

非常感谢! 附言FMS_Csharp_GUI 是程序的名称。

【问题讨论】:

  • 什么是 FMS_Csharp_GUI?这看起来像是某种第三方工具。此外,您真的不应该以纯文本形式存储密码,它们应该被加盐和散列。我还建议定义参数的数据类型和大小,而不是 AddWithValue。它有时会导致性能问题甚至出错。 blogs.msmvps.com/jcoehoorn/blog/2014/05/12/…
  • 海上编辑,是的,我知道您不会将密码保存为纯密码,这只是一个测试。我会看看 addWithValue。关于问题本身的任何信息?
  • 这通常是由于在您定义为数据表的主键的列中的结果集中获得了 NULL 或重复值。谷歌搜索你的错误信息超过 20,000 次点击。前几个都提到了我刚才所做的。
  • 另外,我希望你不打算使用 MD5 作为你的加密方法。它真的很旧,已经坏了很长时间了。
  • 我不认为它返回任何空值...

标签: c# sql sql-server datagrid


【解决方案1】:

由于某种原因,我不知道它不起作用。但现在确实如此,在我尝试这样做之后:

            using (connection = new SqlConnection(sqlConnectionString))
        using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT ID,Name,PasswordSHA256, IsAdmin"
            + " From UsersTable", connection))
        {
            //get data
            DataTable user = new DataTable();
            adapter.Fill(user);
            usersTableDataGrid.DataContext = user;
        }

然后我突出显示了这段代码,并使用了上面的那个,它起作用了!

也许明白了,为什么让它起作用?

【讨论】:

    猜你喜欢
    • 2012-03-30
    • 1970-01-01
    • 2012-11-10
    • 2012-01-16
    • 1970-01-01
    相关资源
    最近更新 更多