Friday, September 3, 2010

Load csv data to MySQL using BulkLoader

C#.Net and MySql ????? You don't need to scratch your head, since MySql developer team is kind enough to provide the ADO.NET connector. You can download the connector from the following http://dev.mysql.com/downloads/connector/net/5.1.html

Tats about MySqlConnector, lets come back to the program. 

Params to program
  1. The csv/txt file path

 static void Main(string[] args)
        {
            string connStr = "server=localhost;user id=user id;password=password;database=database";
            // MySql Connection Object
            MySqlConnection conn = new MySqlConnection(connStr);

            //  csv file path
            string file = @"filepath";

            // MySQL BulkLoader
            MySqlBulkLoader bl = new MySqlBulkLoader(conn);
            bl.TableName = "tablename";
            bl.FieldTerminator = "|"; This can be {comma,tab,semi colon, or other character}
            bl.LineTerminator = "\n";
            bl.FileName =file; 

            try
            {
                Console.WriteLine("Connecting to MySQL...");
                conn.Open();

                // Upload data from file
                int count = bl.Load();
                Console.WriteLine(count + " lines uploaded.");

                conn.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            Console.WriteLine("Done.");
            Console.ReadLine();
         
        }

No comments:

Post a Comment