[英]Unable to insert data from c# to mysql database
我有這個問題。 我在MySql中創建2個表,這些表與外鍵連接在一起。 我想從C#將數據插入表中。
表人
id-int,自動遞增,主鍵
first_name-varchar
last_name-varchar
表地址
id-自動遞增,主鍵
城市-瓦爾恰
steet_number-varchar
person_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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.