簡體   English   中英

System.Data.dll c# 中發生類型為“System.Data.OleDb.OleDbException”的未處理異常

[英]An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll c#

我已經創建了 Windows 窗體,該窗體的功能是將信息添加到數據庫中。 但是,我有一個問題。 當我在“產品代碼”列中輸入像“SM0001”這樣的數字並按回車鍵時,它會將數據存儲到數據庫中,當我像之前輸入的一樣輸入相同的數字時,它不會阻止用戶喜歡輸入的“產品代碼”已存在於數據庫中。 所以,這是我當前的數據庫(顯示在系統的 datagridview 中):

在此處輸入圖片說明

如您所見,“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 - 主鍵

數據庫.about.com

在執行AddDatabase之前,您應該檢查該鍵是否已經存在於數據庫中。 你可以用很多不同的方式來做到這一點。

  1. 在數據庫上執行選擇

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

    如果該查詢產生一個結果,那么產品代碼已經存在於數據庫和查詢應該被執行

  2. 檢查您的 datagridview 的數據源

    作為 datagridview 的數據源,您可能正在提供一個列表/數據集。 您可以檢查列表中是否存在新輸入的 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所有記錄

在執行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並從事件處理程序中調用它。

您可以有 2 個方法,然后是Exists(id)Add(...) ,因此如果您可以進行簡單的重復檢查:

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

如果您的錯誤是在 system.data.dll 中發生的類型為“system.data.oledb.oledbexception”的未處理異常附加信息:溢出 DB 中的 cloumn 很少用於注釋或數字請將 cloumn 格式更改為更大的數字 ---- > 整數上到雙坦克

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM