Answer to Question #39124 in C++ for Salman Rakin

Question #39124
Could you please make a program to read data from attached file and save the data to a data base in C++ ?
1
Expert's answer
2014-03-04T10:52:26-0500
#include <string>

#include <vector>
#include <iostream>
#include <fstream>


#include "include/cppconn/driver.h"
#include "include/cppconn/connection.h"
#include "include/cppconn/statement.h"
#include "include/cppconn/prepared_statement.h"
#include "include/cppconn/resultset.h"
#include "include/cppconn/metadata.h"
#include "include/cppconn/resultset_metadata.h"
#include "include/cppconn/exception.h"
#include "include/cppconn/warning.h"


#define DBHOST "https://127.0.0.1:3306"
#define USER "root"
#define PASSWORD "admin"
#define DATABASE "team"


using namespace sql;
using namespace std;


class Person {
public:
string first_name;
string last_name;
int age;


public:
Person(string _first_name, string _last_name, int _age) {
first_name = _first_name;
last_name = _last_name;
age = _age;
}
};


class FileToDatabaseProcessor {
private:
vector<Person> personsList;


public:
void readPersonsListFromFile(string filename) {
ifstream file;
string line;
file.open(filename);
if (file.is_open())
{
while (! file.eof() )
{
getline(file, line);


unsigned space = line.find(" ");
string first_name = line.substr(0, space);
line = line.substr(space + 1);
space = line.find(" ");


string last_name = line.substr(0, space);
string age = line.substr(space + 1);


personsList.push_back(Person(first_name, last_name, atoi(age.c_str())));
}
file.close();
}
else cout << "Unable to open file";
}


void writeToDatabase() {
Driver *driver;
Connection *con;
PreparedStatement *prep_stmt;


int updatecount = 0;


try {
driver = get_driver_instance();
con = driver -> connect(DBHOST, USER, PASSWORD);
con -> setSchema(DATABASE);


vector<Person>::iterator i = personsList.begin();
while (i != personsList.end()) {
Person p = *i;

prep_stmt = con -> prepareStatement ("INSERT INTO Person (first_name, last_name, age) VALUES (?,?,?)");

prep_stmt -> setString (1, i->first_name);
prep_stmt -> setString (2, i->last_name);
prep_stmt -> setInt(3, i->age);


updatecount = prep_stmt -> executeUpdate();
++i;
}

delete prep_stmt;
con -> close();
delete con;


} catch (SQLException &e) {
cout << "ERROR: SQLException; " << endl;
} catch (std::runtime_error &e) {
cout << "ERROR: runtime_error;" << endl;
}
}


};


int _tmain(int argc, _TCHAR* argv[])
{
FileToDatabaseProcessor proc = FileToDatabaseProcessor();
proc.readPersonsListFromFile("1.txt");
proc.writeToDatabase();
system("pause");
return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS