提问人:Gardinero 提问时间:4/7/2020 最后编辑:Gardinero 更新时间:4/8/2020 访问量:954
C# - SQL Server:INSERT 语句与 FOREIGN KEY 约束冲突 - 未处理的异常
C# - SQL Server: INSERT statement conflicted with FOREIGN KEY constraint - Unhandled Exception
问:
我编写了一个小型 C# 应用程序,它读取 Excel 文件,并应将数据导入到现有的 SQL Server 数据库中。
由于应插入条目的表中存在外键约束,因此我已经使用
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
我能做些什么来防止这种行为?
例外情况:
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
答:
0赞
fsbflavio
4/7/2020
#1
“当对表执行 INSERT 命令时,会发生此错误,并且该表的一列引用了另一个表上的主键,并且插入到该特定列的值在另一个表中不存在。”
检查外键引用的行是否存在。
看到这个,我相信它会帮助你:http://www.sql-server-helper.com/error-messages/msg-547-insert.aspx
0赞
Gardinero
4/8/2020
#2
真丢人!该异常是由另一个 sql 查询引起的,该查询是在上述查询之后直接调用的。所以我能够修复它。
但我仍然不明白的是,为什么 ThreadExceptionDialog 没有出现在我的开发机器上,尽管我也在它上运行了完全相同的版本......
感谢您的帮助。
评论