Vlad Poncea
Vlad Poncea

Reputation: 359

How to import data from a TXT file to an Access Database

I am trying to import data from a txt file to an Access Database but it imports only the first record of the file. Here is the code

I also tried a harder method by storing the data in 3 arrays(because I have 3 column) and I checked them and they had the correct data but when I insert it into access it imports only the first record 6 times(this is how much records I have on the txt file)

OleDbCommand cmd = new OleDbCommand("INSERT into Utilizatori (Nume, Parola, Email) values(@nume, @parola, @email)", conn);
string[] values;
foreach (string line in File.ReadLines(@"D:\vlad\c#\centenar\Centenar\bin\Debug\utilizatori.txt"))
{
    values = line.Split('*');
    cmd.Parameters.Add("@nume", OleDbType.VarChar).Value = values[0];
    cmd.Parameters.Add("@parola", OleDbType.VarChar).Value = values[1];
    cmd.Parameters.Add("@email", OleDbType.VarChar).Value = values[2];
    cmd.ExecuteNonQuery();
}

Upvotes: 0

Views: 604

Answers (1)

Steve
Steve

Reputation: 216243

In the loop you continuosly add the parameters to the command. So after the first loop the command has 3 parameters, after the second one you have 6 parameters and on, but when the command is executed, only the first three are considered and thus you end inserting always the same values.

You could clear the parameters collection at each loop with

cmd.Parameters.Clear();

But it is better to define the parameters outside the loop just one time, while inside the loop, you could just replace the values.

OleDbCommand cmd = new OleDbCommand("INSERT into Utilizatori (Nume, Parola, Email) values(@nume, @parola, @email)", conn);
cmd.Parameters.Add("@nume", OleDbType.VarChar);
cmd.Parameters.Add("@parola", OleDbType.VarChar);
cmd.Parameters.Add("@email", OleDbType.VarChar);
string[] values;
foreach (string line in File.ReadLines(@"D:\vlad\c#\centenar\Centenar\bin\Debug\utilizatori.txt"))
{
    values = line.Split('*');
    cmd.Parameters["@nume"].Value = values[0];
    cmd.Parameters["@parola"].Value = values[1];
    cmd.Parameters["@email"].Value = values[2];
    cmd.ExecuteNonQuery();
}

Upvotes: 1

Related Questions