わたがし食べたい

アイドルマスター卯月Pによるつれづれなる技術ブログ(仮)

libpqxx で レコードを一行ずつ表示する

一行ずつカンマ区切りで表示する

ソースコード

#include "ClibpqxxMap.h"
#include <iostream>
#include <pqxx/pqxx>
using namespace std;
using namespace pqxx;

int main()
{
try {
connection Conn("dbname=postgres user=postgres");
work T(Conn);
result r(T.exec("select * from test"));

//一行ずつ表示する
const int num_rows = r.size();
for (int rownum = 0; rownum < num_rows; ++rownum)
{
std::cout << "r.size" << std::endl;
const pqxx::row row = r[rownum];
const int num_cols = row.size();
for (int colnum = 0; colnum < num_cols; ++colnum)
{
const pqxx::field field = row[colnum];
string fieldStr = field.c_str();
if (colnum +1 < num_cols) {
fieldStr = fieldStr + ",";
}
std::cout << fieldStr ;
}
std::cout << std::endl;
}
//T.commit();
Conn.disconnect();
}
catch (const exception &e) {
cerr << e.what() << endl;
return 1;
}
return 0;
}

実行結果

f:id:kuroaka3:20180701223155p:plain

 

さらに改良し、1カラムずつ出力

ソースコード

 

#include "ClibpqxxMap.h"
#include <iostream>
#include <pqxx/pqxx>
using namespace std;
using namespace pqxx;

/*
自作split
*/
std::vector<std::string> split(const std::string input, char delimiter)
{
std::istringstream stream(input);

std::string field;
std::vector<std::string> result;
while (std::getline(stream, field, delimiter)) {
result.push_back(field);
}
return result;
}

int main()
{
try {
connection Conn("dbname=postgres user=postgres");
work T(Conn);
result r(T.exec("select * from test")); const int num_rows = r.size(); for (int rownum = 0; rownum < num_rows; ++rownum)
{
const pqxx::row row = r[rownum];
const int num_cols = row.size();
string record = ""; for (int colnum = 0; colnum < num_cols; ++colnum)
{
const pqxx::field field = row[colnum];
string fieldStr = field.c_str(); //次も値があるかチェック
int chCnt = colnum;
record = record + fieldStr;
if (chCnt +1 < num_cols) {
record = record + ",";
}
}
cout << endl; std::cout << "record : " << record << endl; // カンマで区切る
cout << "---split----" << endl;
for (const string& s : split(record, ',')) {
cout << s << endl;
}
}
cout << endl;
//T.commit();
Conn.disconnect();
}
catch (const exception &e) {
cerr << e.what() << endl;
return 1;
}
return 0;
}


実行結果

f:id:kuroaka3:20180702001540p:plain