【问题标题】:Insert foreign key into table with SQL query using C#使用 C# 使用 SQL 查询将外键插入表中
【发布时间】:2020-01-24 15:31:09
【问题描述】:

我有一个包含 3 个表 IdentificationIdentification_groupGroup 的数据库。

Identification_group 表有 2 个外键列,Identificaiton_idGroup_id

在我的表单中,您可以选择组号,它将正确的 Group_id 返回到Identification_group 表。

是否可以编写一个 SQL 查询,使用最后一个 Identification_idGroup_id(来自我表单中的选择字段)并将其写入 Identification_group 表?

string sqlquery1 = "Insert into [dbo].[identification_group] (fk_group_id,fk_identification_id values (@fk_group_id,@fk_identification_id;";
            SqlCommand schreiben = new SqlCommand(sqlquery1, myConnection);
            myConnection.Open();
            schreiben.Parameters.AddWithValue("@fk_identification_id", intidentification_id);
            schreiben.Parameters.AddWithValue("@fk_group_id", Wil_Jls_idComboBox.SelectedValue);
schreiben.CommandText = sqlquery;
schreiben.ExecuteNonQuery();
            myConnection.Close();

抱歉格式错误,第一次在这里发帖。

提前谢谢你

【问题讨论】:

  • 您只需要使用 schreiben.ExecuteNonQuery() 执行命令
  • 忘记添加了,现在更新我的代码。制作问题的行是 "schreiben.Parameters.AddWithValue("@fk_identification_id", intidentification_id);"我想我需要使用“lastSelectedId”之类的东西,但我似乎无法让它发挥作用。
  • schreiben.Parameters.AddWithValue("@fk_identification_id", intidentification_id); 中删除@ 符号-您只需要SQL 查询语句中的@ 符号,而不需要在实际的C# 代码中。您的 SQL 语句中也没有右括号

标签: c# sql foreign-keys sqlcommand


【解决方案1】:

请尝试以下方法:

您的 SQL 语句存在问题,您没有关闭括号。此外,您只需要在 SQL 语句中使用 @ 符号,而在 C# 代码中不需要。

// Create the query
string query = "Insert into [identification_group] (fk_group_id, fk_identification_id) values (@fk_group_id, @fk_identification_id)";

// Create the SQL command
SqlCommand schreiben = new SqlCommand(query, myConnection);

// Open the SQL connection
myConnection.Open();

// Bind the parameters
schreiben.Parameters.AddWithValue("fk_identification_id", intidentification_id);
schreiben.Parameters.AddWithValue("fk_group_id", Wil_Jls_idComboBox.SelectedValue);

// Bind the command
schreiben.CommandText = query;

// Execute the command
schreiben.ExecuteNonQuery();

// Close the connection
myConnection.Close();

【讨论】:

    猜你喜欢
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 2021-09-15
    • 2016-05-20
    • 2017-11-25
    • 2019-04-13
    相关资源
    最近更新 更多