Click here to Skip to main content
15,913,709 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;

namespace texttodb3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string[] lines = File.ReadAllLines("c:Users\\Techsoft\\Desktop\\db.txt");
            foreach (var line in lines)
            {
                var data = line.Split(new[] { ',' }, 4);
                int Id = int.Parse(data[0].Trim());
                int age = int.Parse(data[1].Trim());

                string name = data[2].Trim();
                StoreRecord(Id, age, name);
            }

        }
        private void StoreRecord(int Id, int age, string name)
        {
            var conStr = "server=localhost; database=neww; password=techsoft; User Id=root;";
            using (var connection = new MySqlConnection(conStr))
            using (var command = connection.CreateCommand())
            {
                connection.Open();
                command.CommandText =
                @"INSERT INTO neww
            (Id, age, name)
          VALUES
            (@Id, @age, @name)";
                command.Parameters.AddWithValue("@Id", Id);
                command.Parameters.AddWithValue("@age", age);
                command.Parameters.AddWithValue("@name", name);

                command.ExecuteNonQuery();
            }
        }
    }
}
Posted
Comments
navin ks 4-Mar-13 6:54am    
nice job..
now im getting other error at
int age = int.Parse(data[1].Trim());
Input string was not in a correct format.

1 solution

The code doesn't look like it has a major problem - but the error message implies that it is a DB problem. The reason I say that is that the ID field is being given an int - which is a value type and cannot be null, so the "null id not allowed" message must be coming from a different column in your table.

Start by putting a breakpoint on the first line in StoreRecord and looking at the three parameters - I'm betting they are ok.
So single step through the code, and if the error comes at the ExecuteNonQuery statement then you need top look at your neww table definition and ensure it only has three columns. I'd be pretty sure there is a fourth that you aren't setting.
 
Share this answer
 
Comments
navin ks 4-Mar-13 7:20am    
now no errors.. but in mysql db im getting null
OriginalGriff 4-Mar-13 7:28am    
Where? Which column?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900