0

我有这个问题。我在 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”列中?或者也许我在其他地方错了?

4

1 回答 1

1

一口气,您可以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在下一个查询中使用结果。

于 2013-07-14T14:06:43.097 回答