INSERT语句与FOREIGN KEY约束冲突

时间:2011-06-15 16:14:52

标签: sql database vb.net foreign-keys

myCommand = New SqlCommand(
"INSERT INTO tblBook(BookCode, BookTitle, Author, PublishingYear, 
                     Price, EnterDate, CatID, RackID, Amount) 
VALUES('" & txtBookCode.Text & "','" & 
            txtTitle.Text & "','" & 
            txtAuthor.Text & "','" & 
            txtPublishYear.Text & "','" & 
            txtPrice.Text & "', #" & 
            txtEnterDate.Text & "#, " & 
            txtCategory.ValueMember & "," & 
            txtRack.ValueMember & "," & 
            txtAmount.Text & ")"
, myConnection)

错误是:

  

INSERT语句与FOREING KEY约束“FK_tblBook_tblCategory”冲突。该       数据库“CIEDC”,表“dbo.tblCategory”,列“CatID”发生冲突。       声明已经终止。

那是因为我的数据库的关系吗?

如何解决这个问题?

3 个答案:

答案 0 :(得分:2)

txtCategory.ValueMember的值似乎与数据库中的有效类别ID不对应。

答案 1 :(得分:0)

另外,如果您不了解SQL注入,请阅读它。

SQL injection - please explain

连接变量以构建SQL查询是将数据库从您身下删除的好方法。

答案 2 :(得分:0)

我认为有两种情况:

1

在表 dbo.tblBook 中,它有一个名为 CatID 的列充当dbo.tblCategory表的外键引用。您似乎正在尝试使用尚未创建的 CatID 属性。如果是,请返回并首先创建 CatID

2

也许有多个与您的表相关的外键。 如果您正在使用sql server,那么sql语句将帮助您找到所有这些,请查看并删除剩余的,祝您好运!

    USE <database_name>;  
GO  
SELECT   
    f.name AS foreign_key_name  
   ,OBJECT_NAME(f.parent_object_id) AS table_name  
   ,COL_NAME(fc.parent_object_id, fc.parent_column_id) AS constraint_column_name  
   ,OBJECT_NAME (f.referenced_object_id) AS referenced_object  
   ,COL_NAME(fc.referenced_object_id, fc.referenced_column_id) AS referenced_column_name  
   ,is_disabled  
   ,delete_referential_action_desc  
   ,update_referential_action_desc  
FROM sys.foreign_keys AS f  
INNER JOIN sys.foreign_key_columns AS fc   
   ON f.object_id = fc.constraint_object_id   
--WHERE f.parent_object_id = OBJECT_ID('HumanResources.Employee'); 
GO 
SELECT 
f.name AS foreign_key_name 
,OBJECT_NAME(f.parent_object_id) AS table_name 
,COL_NAME(fc.parent_object_id, fc.parent_column_id) AS constraint_column_name 
,OBJECT_NAME (f.referenced_object_id) AS referenced_object 
,COL_NAME(fc.referenced_object_id, fc.referenced_column_id) AS referenced_column_name 
,is_disabled 
,delete_referential_action_desc 
,update_referential_action_desc 
FROM sys.foreign_keys AS f 
INNER JOIN sys.foreign_key_columns AS fc 
ON f.object_id = fc.constraint_object_id 
--WHERE f.parent_object_id = OBJECT_ID('HumanResources.Employee');