Importing text file to database

This is the forum for miscellaneous technical/programming questions.

Moderator: 2ffat

Importing text file to database

Postby bhanu » Sun May 01, 2005 11:09 pm

The following query imports a comma delimited text file data into table with first five fields data being stored in F1, F2, F3, F4 and F5.

LOAD DATA LOCAL INFILE 'SAMPLE.TXT' INTO TABLE SAMPLE_TABLE FIELDS TERMINATED BY ',' ESCAPED BY '\\' LINES TERMINATED BY '\n' (F1, F2, F3, F4, F5);

How to load text file data to specific columns in table (ex. First five columns in text to is to be imported to last five columns in table).
bhanu
 

Data Import via STL getline

Postby 2ffat » Thu May 05, 2005 11:08 am

If I understand you correctly, you have a text file that you want to import into a table. Is this correct?

I do this via the STL getline function. The first thing I do is open the file via a stream. Next, I get the full line of text using a getline. Finally, I apply the getline to the line, via a string stream, in order to break it apart.

For example, the following is a snippet from one of my programs that takes a comma delimited text file and breaks it into parts to be put into a table.
Code: Select all
std::ifstream ParFile; // open a stream
ParFile.open("Sample.txt");
if (!ParFile)                   // Error opening file stream
{
    // Process error reporting here
Application->MessageBox("Cannot open file for reading", "File Error", MB_OK); // For example
}                               // Error opening file stream
else                            // Work on import
{
    std::string ImpLine; // This string will hold each line from the file
    while (std::getline(ParFile, ImpLine, '\n'))  // Loop while there is data to get
    {
        // Process input string into parts via string stream
        std::istringstream StrLine(ImpLine); // create a string stream
        std::string F1Str; // first field
        std::getline(StrLine,F1Str,','); // Find the comma for the first field

        std::string F2Str;
        std::getline(StrLine,F2Str,','); // Second field

        // Repeat for each field in text file
.
.
.
       // After you have each field, you can put the data into a table
   }         // Loop
}            // Work on import


As I mentioned, this is a modified snippet and you will have to change it to suit your needs.

Also, don't forget to #include <fstream> and #include <sstream>.
James P. Cottingham

Look at me still talking
when there is science to do.
User avatar
2ffat
Forum Mod
Forum Mod
 
Posts: 444
Joined: Wed Jun 23, 2004 7:07 am
Location: South Hill, VA


Return to Technical

Who is online

Users browsing this forum: No registered users and 21 guests