jumbojs
jumbojs

Reputation: 4868

Saving a text file to a SQL database without column names

I am reading a text file in C# and trying to save it to a SQL database. I am fine except I don't want the first line, which is the names of the columns, included in the import. What's the easiest way to exclude these?

The code is like this

while (textIn.Peek() != -1)
{
   string row = textIn.ReadLine();
   string[] columns = row.Split('   ');
   Product product = new Product();
   product.Column1 = columns[0];
   etc.....
   product.Save();
}

thanks

Upvotes: 0

Views: 1569

Answers (5)

Turbo_Aspiration
Turbo_Aspiration

Reputation:

For future reference have a look at this awesome package: FileHelpers Library

I can't add links just yet but google should help, it's on sourceforge

It makes our lives here a little easier when people insist on using files as integration

Upvotes: 0

Beatles1692
Beatles1692

Reputation: 5320

Here's my suggestion:

string[] file_rows;
using(var reader=File.OpenText(filepath))
{
file_rows=reader.ReadToEnd().Split("\r\n");
reader.Close();
}

for(var i=1;i<file_rows.Length;i++)
{
var row=file_rows[i];
var cells=row.Split("\t");
....
}

Upvotes: 1

workmad3
workmad3

Reputation: 25707

Pass a flag into the program (in case in future the first line is also data) that causes the program to skip the first line of text.

If it's the same column names as used in the database you could also parse it to grab the column names from that instead of hard-coding them too (assuming that's what you're doing currently :)).

As a final note, if you're using a MySQL database and you have command line access, you may want to look at the LOAD DATA LOCAL INFILE syntax which lets you import pretty arbitrarily defined CSV data.

Upvotes: 0

TheTXI
TheTXI

Reputation: 37905

If you are writing the code yourself to read in the file and then importing...why don't you just skip over the first line?

Upvotes: 2

KM.
KM.

Reputation: 103637

how are you importing the data? if you are looping in C# and inserting them one at a time, construct your loop to skip the first insert!

or just delete the first row inserted after they are there.

give more info, get more details...

Upvotes: 0

Related Questions