我有这个问题。我在 MySql 中创建了 2 个表,它们用外键连接在一起。我想从 c# 在表中插入数据。
表人员
id - int、自动递增、主键
first_name - varchar
last_name - varchar
表地址
id - 自动递增,主键
city - varchar
steet_number - varchar
people_id - 外键
string mySqlString = "server=localhost;uid=root;pwd=root;database=address_book;";
MySqlConnection conn = new MySqlConnection(mySqlString);
try
{
conn.Open();
string insertPerson = "INSERT INTO persons(first_name, last_name) VALUES (@first_name, @last_name)";
string insertAddress = "INSERT INTO addresses(city, street_number, persons_id) VALUES (@city, @street_number, @persons_id)";
MySqlCommand command = new MySqlCommand(insertPerson, conn);
MySqlCommand secondCommand = new MySqlCommand(insertAddress, conn);
command.Parameters.AddWithValue("@first_name", TextBox1.Text);
command.Parameters.AddWithValue("@last_name", TextBox2.Text);
int id = Convert.ToInt32(command.LastInsertedId);
command.ExecuteNonQuery();
secondCommand.Parameters.AddWithValue("@city", TextBox3.Text);
secondCommand.Parameters.AddWithValue("@street_number", TextBox4.Text);
secondCommand.Parameters.AddWithValue("@persons_id", id);
secondCommand.ExecuteNonQuery();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Clone();
}
但这不起作用,我应该如何从主键中获取最后插入的值以将该值插入“persons_id”列中?或者也许我在其他地方错了?