2

i read file through c# and the format of file is this.
INPUT FILE

00001740,      0.125,      0,      able
00001740,      0.125,      0,      unable
00002098,      0,          0.75,   country
00002312,      0,          0,      love    

i want this file in MYSQL Database. i write the code which store each line in each ROW of database. but the following code WRITE only the first line of the text file

 private void button1_Click(object sender, EventArgs e)
        {
            string MyConString = "server=localhost;" +
                "database=zahid;" + "password=zia;" +
                "User Id=root;";
            MySqlConnection connection = new MySqlConnection(MyConString);
            MySqlCommand command = connection.CreateCommand();
            MySqlDataReader Reader;
            connection.Open();
            StreamReader reader = new StreamReader("D:\\out.txt");

            string line;
            while ((line = reader.ReadLine()) != null)
            {   
                string[] parts = line.Split(',');
                command.CommandText = "insert into score(POS_ID,Pos,Neg,Word) values('" + parts[1] + "','" + parts[2] + "','" + parts[3] + "','" + parts[4] + "')";



                Reader = command.ExecuteReader();      
            }
        } 

this code return only the First line , but i want that all lines of text file store in the Database . thanks in advance

0

1 Answer 1

4

Try cleaning the mess:

private void button1_Click(object sender, EventArgs e)
{
    string[] lines = File.ReadAllLines("D:\\out.txt");
    foreach (var line in lines)
    {
        var data = line.Split(new[] { ',' }, 4);
        int posId = int.Parse(data[0].Trim());
        double pos = double.Parse(data[1].Trim());
        double neg = double.Parse(data[2].Trim());
        string word = data[3].Trim();
        StoreRecord(posId, pos, neg, word);
    }
}

private void StoreRecord(int posId, double pos, double neg, string word)
{
    var conStr = "server=localhost; database=zahid; password=zia; User Id=root;";
    using (var connection = new MySqlConnection(conStr)) 
    using (var command = connection.CreateCommand())
    {
        connection.Open();
        command.CommandText = 
        @"INSERT INTO score 
            (POS_ID, Pos, Neg, Word) 
          VALUES 
            (@posId, @pos, @neg, @word)";
        command.Parameters.AddWithValue("@posId", posId);
        command.Parameters.AddWithValue("@pos", pos);
        command.Parameters.AddWithValue("@neg", neg);
        command.Parameters.AddWithValue("@word", word);
        command.ExecuteNonQuery();
    }
}

Things to notice:

  • separating the database insert logic into a dedicated method to avoid doing parsing and db inserts in the same place
  • usage of using statemenets to properly dispose IDisposable resources such as connections and commands
  • usage of parametrized queries to avoid SQL injection

Also you probably don't want to be rolling your own CSV parser using String.Split but use a real CSV parser instead.

If the CSV file is big you could read it one line at a time to avoid loading it in memory at once:

private void button1_Click(object sender, EventArgs e)
{
    using (var stream = File.OpenRead("D:\\out.txt"))
    using (var reader = new StreamReader(stream))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            var data = line.Split(new[] { ',' }, 4);
            int posId = int.Parse(data[0].Trim());
            double pos = double.Parse(data[1].Trim());
            double neg = double.Parse(data[2].Trim());
            string word = data[3].Trim();
            StoreRecord(posId, pos, neg, word);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.