首页 > 解决方案 > 无法将数据插入 SQL Server 中的外键

问题描述

ClassTable:**

CREATE TABLE ClassTable 
(
    className varchar(255) NOT NULL PRIMARY KEY,  
    classFee  int,
    academicYear int
);

StudentTable

CREATE TABLE StudentTable  
(
    id int NOT NULL IDENTITY(1,1) PRIMARY KEY,
    firstName varchar(255) NOT NULL,
    lastName varchar(255),
    fatherName varchar(255),
    fatherNo varchar(255),
    motherName varchar(255),
    motherNo varchar(255),
    dob date,
    dor date,
    gender varchar(255),
    className varchar(255),
    healthInsuranceNo varchar(255),
    resAddress varchar(255),
    photo Image,

    CONSTRAINT FK_StudentTable 
        FOREIGN KEY (className) REFERENCES ClassTable(className)
);

C#代码:

cmd = new SqlCommand("INSERT INTO StudentTable (firstName, lastName, fatherName, fatherNo, motherName, motherNo, dob, dor, gender, className, healthInsuranceNo, resAddress, photo) VALUES (@firstName, @lastName, @fatherName, @fatherNo, @motherName, @motherNo, @dob, @dor, @gender, @className, @healthInsuranceNo, @resAddress, @photo)", con);
con.Open();

cmd.Parameters.AddWithValue("@firstName", txt_FirstName.Text);
cmd.Parameters.AddWithValue("@lastName", txt_LastName.Text);
cmd.Parameters.AddWithValue("@fatherName", txt_FatherName.Text);
cmd.Parameters.AddWithValue("@fatherNo", txt_FatherNo.Text);
cmd.Parameters.AddWithValue("@motherName", txt_MotherName.Text);
cmd.Parameters.AddWithValue("@motherNo", txt_MotherNo.Text);
cmd.Parameters.AddWithValue("@dob", dateTimePickerDOB.Text);
cmd.Parameters.AddWithValue("@dor", dateTimePickerDOR.Text);
cmd.Parameters.AddWithValue("@gender", cmb_Gender.Text);
cmd.Parameters.AddWithValue("@className", cmb_Class.Text);
cmd.Parameters.AddWithValue("@healthInsuranceNo", txt_HealthInsurance.Text);
cmd.Parameters.AddWithValue("@resAddress", txt_Address.Text);

MemoryStream ms = new MemoryStream();
img_Box.Image.Save(ms, img_Box.Image.RawFormat);
cmd.Parameters.AddWithValue("@photo", ms.ToArray());

cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Accountant successfully registered.");

当我手动将查询写入 SQL Server 时,它允许我将数据插入外键列 ( className),但是当我尝试从 C# Winforms 应用程序插入时,我收到此错误:

INSERT 语句与 FOREIGN KEY 约束“FK_StudentTable”冲突。冲突发生在数据库“SchoolDatabase”、表“dbo.ClassTable”、列“className”中。

我使用此查询在数据库中手动输入一条记录,它起作用了:

INSERT INTO StudentTable (firstName, className) 
VALUES ('name here', 'class one');

标签: c#sql-server

解决方案


推荐阅读