C#-SQL Server:INSERT语句与FOREIGN KEY约束冲突-未处理的异常

问题描述 投票:0回答:1

我编写了一个小型C#应用程序,该应用程序读取Excel文件,并将数据导入到现有的SQL Server数据库中。

由于应该在其中插入条目的表中有外键约束,我已经通过使用]在我的SQL查询中直接防止了此错误。

IF NOT EXISTS (SELECT * FROM [dbo].[InvoiceAccount] 
               WHERE Caption = @Caption) 
    INSERT INTO [dbo].[InvoiceAccount] (Caption, IdInvoiceAccountType, Account)     
    VALUES (@Caption, @IdInvoiceAccountType, @Account)

在开发计算机上,执行我的应用程序并尝试插入Excel工作表可以正常工作,没有任何问题。

虽然我在另一台PC上执行相同的操作,但确实得到了一个[[ThreadExceptionDialog

,尽管SQL查询按预期方式工作。C#代码如下:

foreach (DataGridViewRow row in dataGridViewToInsert.Rows) { using (SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings.Get("connectionString"))) { using (SqlCommand cmd = new SqlCommand("IF NOT EXISTS (SELECT * FROM [dbo].[InvoiceAccount] WHERE Caption = @Caption) INSERT INTO [dbo].[InvoiceAccount] (Caption, IdInvoiceAccountType, Account) VALUES (@Caption, @IdInvoiceAccountType, @Account)", con)) { Debug.WriteLine(cmd.CommandText); cmd.Parameters.AddWithValue("@Caption", row.Cells[1].Value); switch (row.Cells[2].Value) { case "Erlöskonto": case "Revenue account": cmd.Parameters.AddWithValue("@IdInvoiceAccountType", 1); break; case "Kostenkonto": case "Expense Account": cmd.Parameters.AddWithValue("@IdInvoiceAccountType", 2); break; case "Geldkonto": case "Cash Account": cmd.Parameters.AddWithValue("@IdInvoiceAccountType", 3); break; case "Abschreibungskonto": case "Depreciation Account": cmd.Parameters.AddWithValue("@IdInvoiceAccountType", 4); break; default: cmd.Parameters.AddWithValue("@IdInvoiceAccountType", 2); break; }; cmd.Parameters.AddWithValue("@Account", row.Cells[0].Value); con.Open(); addedRows = cmd.ExecuteNonQuery(); con.Close(); } } if (addedRows > 0) { insertedRows = insertedRows + addedRows; } }

所以我真的不明白,我在这里做错了,为什么我只在其他计算机上才得到ThreadExceptionDialog,然后才在我的开发PC上得到它。

我该如何防止这种行为?


例外:

System.Data.SqlClient.SqlException (0x80131904): The INSERT statement conflicted with the FOREIGN KEY constraint "FK_VatType2InvoiceAccount_InvoiceAccount". The conflict occurred in database "easyjob", table "dbo.InvoiceAccount", column 'IdInvoiceAccount'. The INSERT statement conflicted with the FOREIGN KEY constraint "FK_VatType2InvoiceAccount_InvoiceAccount". The conflict occurred in database "easyjob", table "dbo.InvoiceAccount", column 'IdInvoiceAccount'. The INSERT statement conflicted with the FOREIGN KEY constraint "FK_VatType2InvoiceAccount_InvoiceAccount". The conflict occurred in database "easyjob", table "dbo.InvoiceAccount", column 'IdInvoiceAccount'. The INSERT statement conflicted with the FOREIGN KEY constraint "FK_VatType2InvoiceAccount_InvoiceAccount". The conflict occurred in database "easyjob", table "dbo.InvoiceAccount", column 'IdInvoiceAccount'. The INSERT statement conflicted with the FOREIGN KEY constraint "FK_VatType2InvoiceAccount_InvoiceAccount". The conflict occurred in database "easyjob", table "dbo.InvoiceAccount", column 'IdInvoiceAccount'. The INSERT statement conflicted with the FOREIGN KEY constraint "FK_VatType2InvoiceAccount_InvoiceAccount". The conflict occurred in database "easyjob", table "dbo.InvoiceAccount", column 'IdInvoiceAccount'. The INSERT statement conflicted with the FOREIGN KEY constraint "FK_VatType2InvoiceAccount_InvoiceAccount". The conflict occurred in database "easyjob", table "dbo.InvoiceAccount", column 'IdInvoiceAccount'. The statement has been terminated. The statement has been terminated. The statement has been terminated. The statement has been terminated. The statement has been terminated. The statement has been terminated. bei System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) bei System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) bei System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) bei System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) bei System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite) bei System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) bei System.Data.SqlClient.SqlCommand.ExecuteNonQuery() bei ejDatabaseAnonymizer.MasterDataUserControl.buttonImport_Click(Object sender, EventArgs e) bei System.Windows.Forms.Control.OnClick(EventArgs e) bei System.Windows.Forms.Button.OnClick(EventArgs e) bei System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) bei System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) bei System.Windows.Forms.Control.WndProc(Message& m) bei System.Windows.Forms.ButtonBase.WndProc(Message& m) bei System.Windows.Forms.Button.WndProc(Message& m) bei System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) bei System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) bei System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) ClientConnectionId:d94a62b5-fb09-4d31-9561-76b2525c7321 Fehlernummer (Error Number):547,Status (State):0,Klasse (Class):16

我编写了一个小型C#应用程序,该应用程序读取Excel文件,并将数据导入到现有的SQL Server数据库中。由于表中存在外键约束,因此条目应为...
c# sql-server constraints thread-exceptions
1个回答
0
投票
当在一个表上执行INSERT命令并且该表的其中一个列引用另一个表上的主键,并且另一个表中不存在要插入该特定列的值时,会发生此错误。
© www.soinside.com 2019 - 2024. All rights reserved.