我有两个表,第一个表名称为tbl_Account,具有fieldName用户ID,用户名,密码,第二个表名称为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();
}
答案 0 :(得分:0)
您可以通过在SQL端编写以下代码来从tbl_Item表的tbl_Account表中引用UserID。
questions
希望能回答您的问题。
答案 1 :(得分:0)
public void InsertRecord(Account loggedInUser)
{
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", ItemId)); // Why you called GenerateID() second time? It was generated in button1_Click
cmd.Parameters.AddWithValue("@itemName", ItemName);
cmd.Parameters.AddWithValue("@logId", loggedInUser.UserID);
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(); do you really need this?
// someLoggedInUser is Account
item.InsertRecord(someLoggedInUser);
}