首页 > 解决方案 > 如果关系是一对多,我如何在我的外键列上插入值

问题描述

我有两个表,第一个表名是 tbl_Account,有一个字段名 UserID、用户名、密码,第二个表名是 tbl_Item,有一个字段名 ItemID、ItemName、UserID。如何获取 tbl_Account 中 UserID 的值并将其放入 tbl_Item 行 UserID?对登录的用户进行防御。

    public void InsertRecord()
            {
                Connection connection = new Connection();
                try
                {
                    string sql = "INSERT INTO tbl_Item VALUES (@itemId, @itemName, @logId)";
                    MySqlConnection conn = new MySqlConnection(connection.ConnectionString);
                    MySqlCommand cmd = new MySqlCommand(sql, conn);
                    cmd.Parameters.AddWithValue("@itemId", GenerateID());
                    cmd.Parameters.AddWithValue("@itemName", ItemName);
                    cmd.Parameters.AddWithValue("@logId", GenerateIDs());
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    conn.Close();

                    MessageBox.Show("Update Successfully", "Update Record", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception e)
                {
                    MessageBox.Show("An error occurred: " + e, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

//my code for btnAdd
private void button1_Click(object sender, EventArgs e)
        {
            Item item = new Item();

            item.ItemID = item.GenerateID();
            item.ItemName = textBox2.Text;
            item.Account.UserID = item.Account.GenerateID();
            item.InsertRecord();
        }

标签: c#oop

解决方案


您可以通过在 SQL 端编写以下代码来从 tbl_Item 表中的 tbl_Account 表中引用 UserID。

 FOREIGN KEY (UserID) REFERENCES tbl_Account(UserID).

希望这能回答你的问题。


推荐阅读