C#/c#

[ c# ] mysql bulk insert

code094 2023. 1. 1. 17:21

큐에 담긴 데이터 insert 하는데 한번에 하나씩 인서트 하니까 성능 너무 떨어짐

그래서 한번에 여러개 넣을 수 있게 함 

 

auto increment 여부 상관 없음 

와중에 테이블 외래키로 묶여있으면 못 한다는거 같음 

 

public void BulkInsert(ConcurrentBag<string> Rows)
    if (Rows.Count > 0)
    {
        string connection = "Server=ip;User ID=id;Password=pw;Database=db_name;Port=port";
        using (MySqlConnection mConnection = new MySqlConnection(connection))
        {

            StringBuilder sCommand = new StringBuilder("INSERT INTO table (col1, col2, col3, col4, col5, col6, col7, col8, col9," +
                  "col10, col11, col12, col13 ) VALUES ");

            sCommand.Append(string.Join(",", Rows));
            sCommand.Append(";");
            mConnection.Open();

            using (MySqlCommand myCmd = new MySqlCommand(sCommand.ToString(), mConnection))
            {
                myCmd.CommandType = CommandType.Text;
                myCmd.ExecuteNonQuery();
            }
        }
    }
}