如何连接桌子?

时间:2019-03-31 13:03:09

标签: sql-server

我要在我的本地数据库中插入3张表,这将是一个个人理财程序。我不知道如何连接这些。 我收到一个错误:System.Data.SqlClient.SqlException:'INSERT语句与FOREIGN KEY约束冲突“ FK__outflowCash__userID__2739D489我的代码在这里:

CREATE TABLE [dbo].[user] (
    [ID]      INT           IDENTITY (1, 1) NOT NULL,
    [name] VARCHAR (25)  NOT NULL,
    [email]   VARCHAR (40)  NOT NULL,
    [password]  VARCHAR (40) NOT NULL,
    PRIMARY KEY CLUSTERED ([ID] ASC)
);
CREATE TABLE [dbo].[inflowCash] (
    [ID]            INT           IDENTITY (1, 1) NOT NULL,
    [category]  VARCHAR (20)  NOT NULL,
    [amount]     INT           NOT NULL,
    [date]      DATE          NOT NULL,
    [comment] VARCHAR (255) NULL,
    [userID]         INT           NULL,
    PRIMARY KEY CLUSTERED ([ID] ASC),
    FOREIGN KEY ([userID]) REFERENCES [dbo].[user] ([ID]) ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE TABLE [dbo].[outflowCash] (
    [ID]            INT           IDENTITY (1, 1) NOT NULL,
    [category]  VARCHAR (20)  NOT NULL,
    [amount]     INT           NOT NULL,
    [date]      DATE          NOT NULL,
    [comment] VARCHAR (255) NULL,
    [userID]         INT           NULL,
    PRIMARY KEY CLUSTERED ([ID] ASC),
    FOREIGN KEY ([userID]) REFERENCES [dbo].[user] ([ID]) ON DELETE CASCADE ON UPDATE CASCADE
);

2 个答案:

答案 0 :(得分:0)

我的查询:

var conn = new SqlConnection(@"Server=(localdb)\MSSQLLocalDB; AttachDbFileName=|DataDirectory|database.mdf;");
conn.Open();

int id;

var cmd = new SqlCommand($"SELECT  ID,  FROM user WHERE email = '{textboxEmail.Text}'", conn);
var reader = cmd.ExecuteReader();
if (reader.Read())
{
 id = (int)reader[0];
}

conn.Close();

conn.Open()
int amount = int.Parse(textboxbAmount.Text);

var cmd2 = "INSERT INTO outflowCash(category, amount, date, comment, userID) VALUES" +
$"('{comboboxCategory.selectedValue}', '{amount}','{datetimpickerDate.Value.ToString("yyyy-MM-dd")}', +
$" ('{textboxComment.Text}', '{id}');";

 var adapter = new SqlDataAdapter();
 adapter.InsertCommand = new SqlCommand(cmd2, conn);
 adapter.InsertCommand.ExecuteNonQuery();
  conn.Close();

答案 1 :(得分:0)

当您插入outflowCash值时,userID值必须指向id表中的有效user值,因为在该值上指定了“外键”引用outflowCash表。