无法将c#中的数据插入mysql数据库
本文关键字:数据 插入 mysql 数据库 | 更新日期: 2023-09-27 18:22:20
我有这个问题。我在MySql中创建了两个表,它们用外键连接在一起。我想从c#在表中插入数据。
桌上人员
id-int,自动递增,主键
first_name-varchar
last_name-varchar
表地址
id-自动递增,主键
城市-varchar
steet_number-varchar
persons_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"列?或者我在别的地方错了?
您可以在查询中直接使用LAST_INSERT_ID()
:
string insertPerson = "INSERT INTO persons(first_name, last_name) VALUES (@first_name, @last_name);"
+ "INSERT INTO addresses(city, street_number,persons_id) VALUES (@city, @street_number, LAST_INSERT_ID());";
MySqlCommand command = new MySqlCommand(insertPerson, conn);
command.Parameters.AddWithValue("@first_name", TextBox1.Text);
command.Parameters.AddWithValue("@last_name", TextBox2.Text);
command.Parameters.AddWithValue("@city", TextBox3.Text);
command.Parameters.AddWithValue("@street_number", TextBox4.Text);
command.ExecuteNonQuery();
或者,您可以运行2个命令1插入人员并检索ID,另一个插入地址:
string insertPerson = "INSERT INTO persons(first_name, last_name) VALUES (@first_name, @last_name)";
MySqlCommand command = new MySqlCommand(insertPerson, conn);
command.Parameters.AddWithValue("@first_name", TextBox1.Text);
command.Parameters.AddWithValue("@last_name", TextBox2.Text);
command.ExecuteNonQuery();
int id = Convert.ToInt32(command.LastInsertedId);
另一种方法是使用这样的双重查询:
string insertPerson = "INSERT INTO persons(first_name, last_name) VALUES (@first_name, @last_name); SELECT last_insert_id();";
MySqlCommand command = new MySqlCommand(insertPerson, conn);
command.Parameters.AddWithValue("@first_name", TextBox1.Text);
command.Parameters.AddWithValue("@last_name", TextBox2.Text);
int id = Convert.ToInt32(comm.ExecuteScalar());
然后,您可以在下一个查询中使用生成的id
。