c# - System.Data.dll c# 中发生类型为 'System.Data.OleDb.OleDbException' 的未处理异常

标签 c# database winforms ms-access datagridview

我已经创建了窗体,其功能是将信息添加到数据库中。但是,我有一个问题。当我在“产品代码”列中键入“SM0001”这样的数字并按下回车键时,它会将数据存储到数据库中,当我键入与之前键入的数字相同的数字时,它不会阻止用户喜欢输入的“产品代码”已存在于数据库中。所以,这是我当前的数据库(显示在系统的datagridview中):

enter image description here

如您所见,“1”行和“2”行具有相同的“产品代码”。我的问题是:如何防止用户输入相同的数字两次?

我已经将数据库中的主键更改为“产品代码”,但这是我遇到的错误:

错误是:

An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll

Additional information: The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again.

错误是:

cmd.ExecuteNonQuery();

关于这个函数:

private void AddDatabase(object sender, EventArgs e)
        {
            using (OleDbConnection conn = new OleDbConnection(connectionString))
            {
                string query = "INSERT INTO [Table] ([ProductCode], [Description], [Price]) VALUES (@ProductCode, @Description, @Price)";
                conn.Open();
                using (OleDbCommand cmd = new OleDbCommand(query, conn))
                {
                    cmd.Parameters.Add("@ProductCode", System.Data.OleDb.OleDbType.VarChar);
                    cmd.Parameters["@ProductCode"].Value = this.numericTextBox1.Text;
                    cmd.Parameters.Add("@Description", System.Data.OleDb.OleDbType.VarChar);
                    cmd.Parameters["@Description"].Value = this.textBox3.Text;
                    cmd.Parameters.Add("@Price", System.Data.OleDb.OleDbType.Integer);
                    cmd.Parameters["@Price"].Value = this.textBox4.Text;
                    cmd.ExecuteNonQuery(); // The error is here
                    if (_choice.comboBox1.Text == "English")
                    {
                        System.Media.SoundPlayer _sound = new System.Media.SoundPlayer(@"C:\Windows\Media\Windows Exclamation.wav");
                        _sound.Play();
                        DialogResult _dialogResult = MessageBox.Show("Added Successfully!", "Success", MessageBoxButtons.OK);
                        if (_dialogResult == DialogResult.OK)
                        {
                            ViewDatabase(sender, e);
                            ClearTextBoxes(sender, e);
                        }
                    }
                }
                conn.Close();
            }
        }

我想当用户键入相同的“产品代码”时,消息框会出现不允许键入的“产品代码”,因为它存在于数据库中并且不会给出错误(终止程序运行)。

我该如何解决?

谢谢

非常感谢您的回答!

最佳答案

您遇到的错误很正常。您不能将重复项插入主键(它们也不能包含“NULL”)列。有关主键的更多信息:

W3schools - primary key

database.about.com

在执行 AddDatabase 之前,您应该检查 key 是否已存在于数据库中。您可以通过许多不同的方式做到这一点。

  1. 对数据库执行选择

    SELECT TOP 1 ProductCode FROM Table WHERE ProductCode = 'this.numericTextBox1.Text'"
    

    如果此查询产生结果,则产品代码已存在于数据库中并且应该执行查询

  2. 检查 datagridview 的数据源

    作为数据 GridView 的数据源,您可能提供了一个列表/数据集。您可以检查您的列表是否存在您新输入的 ProductCode。您可以在此处使用链接或只是迭代源代码。 (无论什么让你的船漂浮)

    如果你能给我数据源的类型,我可能会提供一个代码示例

  3. 检查您的 Datagridview

    如果您的 datagridview 包含数据库的所有记录,那么您可以迭代行并检查第一列是否包含与新输入的产品代码相同的产品代码。

    有些东西

     foreach (DataGridViewRow row in dgvDataGridView.Rows)
          {
          if(row.Cells[0].Value.toString().equals(this.numericTextBox1.Text))
    
               { 
    
               // Productcode is already present
               // Throw message/exception Or whatever
               break; 
               }
          }
    

我会选择选项 1,因为您的 datagridview/datasource 可能不会显示/保留 Table

中的所有记录

关于c# - System.Data.dll c# 中发生类型为 'System.Data.OleDb.OleDbException' 的未处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21904634/

相关文章:

database - 如何在 Windows 中将用户添加到 PostgreSQL?

database - 将 csv 文件数据加载到表中

c# - 使用 Walker 的别名方法进行加权随机选择

c# - ReSharper 的测试运行程序是否可以配置为不显示 Debug.WriteLine() 消息?

c# 如何处理这种泛型约束?

c# - 使用 Roslyn 替换方法节点

javascript - meteor 未捕获类型错误 : Cannot read property 'helpers' of undefined

c# - 调用 NotifyIcon 的上下文菜单

C# - Winforms - 全局变量

mysql - vb.net登录访问控制