c# - 如果关系是一对多,我如何在我的外键列上插入值
问题描述
我有两个表,第一个表名是 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();
}
解决方案
您可以通过在 SQL 端编写以下代码来从 tbl_Item 表中的 tbl_Account 表中引用 UserID。
FOREIGN KEY (UserID) REFERENCES tbl_Account(UserID).
希望这能回答你的问题。
推荐阅读
- reactjs - 如何将事件侦听器添加到 ref?
- angular - 如何通过 HttpInterceptor 映射 HttpResponseError 值?
- ios - Xcode 11 调试器的奇怪行为 - 有值时将值显示为 nil
- c++ - 在 MSYS2 中编译 libcurl
- macos - NSImage drawInRect 在更快的 MacBook Pro 上慢 10 倍以上?
- html - 标签内的换行符
- java - 骆驼延迟覆盖任何 redeliveryPolicy
- excel - 解析数据以在列中对齐
- java - 使用同一个 WebDriver 对象执行多个 JUnit 测试
- java - Spring Boot 应用程序中的 JVM“EXCEPTION_ACCESS_VIOLATION”崩溃