如何在 MySqlCommand 语句中传递多个变量并在 C# 中插入数据库 table?

How to pass several variables in MySqlCommand statement and insert into database table in C#?

我想做的是获取两个表的PKs,传递给对应的变量,然后添加到FKs列的数据插入中。 当我执行以下代码时,我没有得到想要的结果我做错了什么?

public void Create_data()
        {            
            string max_id = "";
            string max_region_id = "";
            conn.Open();
            string query1 = "SELECT MAX(id) FROM countries";
            MySqlCommand cmd1 = new MySqlCommand(query1, conn);
            max_id = Convert.ToString(cmd1.ExecuteScalar());

            string query2 = "SELECT MAX(id) FROM regions";
            MySqlCommand cmd2 = new MySqlCommand(query2, conn);
            max_region_id = Convert.ToString(cmd2.ExecuteScalar());


            using (MySqlCommand cmd = new MySqlCommand())
            {
                cmd.CommandText = "INSERT INTO countries(country, code) VALUES (@country, @code);" + "INSERT INTO regions(region, country_id) VALUES (@region," + max_id+1 + ");" + "INSERT INTO ports(port,region_id) VALUES (@port," + max_region_id+1 + ");";
                cmd.CommandType = CommandType.Text;
                cmd.Connection = conn;

                cmd.Parameters.Add("@country", MySqlDbType.VarChar).Value = country;
                cmd.Parameters.Add("@code", MySqlDbType.VarChar).Value = code;
                cmd.Parameters.Add("@region", MySqlDbType.VarChar).Value = region;
                cmd.Parameters.Add("@port", MySqlDbType.VarChar).Value = port;

                cmd.ExecuteNonQuery();
                conn.Close();
            }
        }

一旦有多个用户同时插入数据,您的方法就会失效。

改用the LAST_INSERT_ID function

using (MySqlCommand cmd = new MySqlCommand())
{
    cmd.CommandText = @"INSERT INTO countries(country, code) VALUES (@country, @code);" 
    + "INSERT INTO regions(region, country_id) VALUES (@region, LAST_INSERT_ID());" 
    + "INSERT INTO ports(port,region_id) VALUES (@port, LAST_INSERT_ID());";
    
    cmd.CommandType = CommandType.Text;
    cmd.Connection = conn;

    cmd.Parameters.Add("@country", MySqlDbType.VarChar).Value = country;
    cmd.Parameters.Add("@code", MySqlDbType.VarChar).Value = code;
    cmd.Parameters.Add("@region", MySqlDbType.VarChar).Value = region;
    cmd.Parameters.Add("@port", MySqlDbType.VarChar).Value = port;

    cmd.ExecuteNonQuery();
    conn.Close();
}

注意: 您似乎在 class 的字段中存储了一个连接对象。那永远不会结束。相反,您应该在需要的地方创建连接,并将其包装在 using 块中,以确保在您完成连接后立即将其处理掉。