MySQLBulkLoader not inserting any row in mysql db

2.9k views Asked by At
   var bl = new MySqlBulkLoader(mycon);
            bl.TableName = "tblspmaster";
            bl.FieldTerminator = ",";
            bl.LineTerminator = "\r\n";
            bl.FileName = "E://31october//SP//sp_files_sample1//400k sp00 6-19 E.csv";
            bl.NumberOfLinesToSkip = 1;

            var inserted = bl.Load();

I am using this code to upload a csv file in db but its not throwing any exception and inserted always show zero .

dotnetconnector for mysql is already installed and reference is also added .

2

There are 2 answers

0
rahularyansharma On BEST ANSWER

Finally i have used this code and its working for me

string sql = @"load data infile 'E:/a1.csv' ignore into table tblspmaster fields terminated by '' enclosed by '' lines terminated by '\n' IGNORE 1 LINES (sp)";
 MySqlCommand cmd = new MySqlCommand(sql, mycon); 
cmd.CommandTimeout = 5000000; 
cmd.ExecuteNonQuery();
0
sushil suthar On

It may not insert the data, if your csv file and the mysql table columns are not matched. For example if your mysql table has a primary key column with identity key, and generally you won't have this column in csv file.

So in the above case the mysqlloader will not insert the data. To solve this use columns property and add the columns mysql table column names

here is a sample code.

public async Task<bool> MySqlBulkLoaderAsync(string csvFilePath)
    {
        bool result = true;
        try
        {
            using (var conn = new MySqlConnection(_connString + ";AllowLoadLocalInfile=True"))
            {
                var bl = new MySqlBulkLoader(conn)
                {
                    TableName = "patientdetailstagings",
                    Timeout = 600,
                    FieldTerminator = ",",
                    LineTerminator = "\n",
                    FieldQuotationCharacter = '"',
                    FileName = csvFilePath,
                    NumberOfLinesToSkip = 1
                };
                bl.Columns.AddRange(new List<string>() {"Column1", "Column2"});
                var numberOfInsertedRows = await bl.LoadAsync();
            }
            System.IO.File.Delete(csvFilePath);
        }
        catch (Exception ex)
        {
            result = false;
            throw;
        }
        return result;
    }

Note: the column mapping will be done based on the way you have added them in the columns property. In the same order it will access the column value from csv file