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

时间:2014-02-20 10:14:02

标签: c# database winforms ms-access datagridview

我已经创建了windows表单,该函数用于将信息添加到数据库中。但是,我有一个问题。当我在“产品代码”列中输入类似“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();
            }
        }

我想当用户键入相同的“产品代码”时,消息框将显示不允许键入的“产品代码”,因为它存在于数据库中而不会出错(从程序中终止程序)。

我该如何解决?

谢谢

您的回答将非常感谢!

3 个答案:

答案 0 :(得分:2)

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

W3schools - primary key

database.about.com

在执行AddDatabase之前,您应该检查密钥是否已存在于数据库中。你可以用很多不同的方式做到这一点。

  1. 在数据库上执行选择

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

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

  2. 检查datagridview的数据源

    作为datagridview的数据源,您可能正在提供List / Dataset。您可以检查列表中是否存在新输入的ProductCode。你可以在这里使用链接或只是迭代源。 (无论你的船是什么漂浮)

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

  3. 检查您的Datagridview

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

    中的某些内容
     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; 
               }
          }
    
  4. 我会选择选项1,因为datagridview / datasource可能无法显示/保留Table

    中的所有记录

答案 1 :(得分:1)

在执行INSERT之前,您可以检查数据库是否已包含ProductCode(表中似乎是)。

类似的东西(从我的一个项目复制/粘贴代码,但应该清楚)

 var command = new OleDbCommand("SELECT COUNT(*) FROM results WHERE id = ?", _connection);
 command.Parameters.Add("id", OleDbType.Date).Value = id;
 if ((int)command.ExecuteScalar() == 0)
 {
     // not exists
 }

建议:不要使AddDatabase成为事件处理程序,而是创建一个单独的类来处理数据库操作,在那里创建方法AddDatabase并从事件处理程序中调用它。

您可以使用Exists(id)Add(...)两种方法,因此如果您可以执行简单的重复检查:

if(Database.Exists(id))
{
    // show errror
    return;
}
DataBase.Add(...);

答案 2 :(得分:0)

如果您的错误是 system.data.dll中发生了类型为'system.data.oledb.oledbexception'的未处理异常附加信息:溢出 DB中的注释很少用于注释或数字 请更改cloumn格式为更大 数字---->整数从高到双 坦克

相关问题