首页 > 其他分享 >cppconn resultsetmetadata get columns count,get column name,resultset get value

cppconn resultsetmetadata get columns count,get column name,resultset get value

时间:2022-12-18 20:56:16浏览次数:47  
标签:count include name get sql time now mysqlhelper

//Model/mysqlhelper.h
#ifndef __mysqlhelper_h__
#define __mysqlhelper_h__
#include <chrono>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <thread>
#include <unistd.h>
#include <uuid/uuid.h>
#include <mysql/mysql.h>
#include <cppconn/connection.h>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/metadata.h>
#include <cppconn/parameter_metadata.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/resultset.h>
#include <cppconn/resultset_metadata.h>

using namespace std;
using namespace std::chrono;

class mysqlhelper
{
public:  
      string get_time_now();       void mysqlreaddemo();
};

#endif

//model/mysqlhelper.cpp
#include "model/mysqlhelper.h"

string mysqlhelper::get_time_now() { chrono::time_point now = system_clock::now(); chrono::microseconds ms = duration_cast<milliseconds>(now.time_since_epoch()) % 1000; time_t rawTime = system_clock::to_time_t(now); struct tm tmInfo = *localtime(&rawTime); stringstream ss; ss << std::put_time(&tmInfo, "%Y%m%d%H%M%S") << std::setfill('0') << std::setw(3) << ms.count(); string dtStr = ss.str(); ss.str(std::string()); return dtStr; }

void mysqlhelper::mysqlreaddemo() { try { sql::Driver *driver; sql::Connection *conn; sql::ResultSet *res; sql::Statement *stmt; sql::PreparedStatement *pstmt; sql::ResultSetMetaData *resMetaData; driver = get_driver_instance(); conn = driver->connect("tcp://127.0.0.1:3306", "username", "password"); conn->setSchema("db"); stmt = conn->createStatement(); res = stmt->executeQuery("select Idx,Id,Author,Comment,Content,Name,Title from Book"); resMetaData=res->getMetaData(); unsigned int columnsCount= resMetaData->getColumnCount(); while (res->next()) { for(int i=1;i<columnsCount;i++) { cout<<resMetaData->getColumnName(i).asStdString()<<":"<<res->getString(i)<<","; } cout<<resMetaData->getColumnName(columnsCount).asStdString()<<":"<<res->getString(columnsCount); cout<<endl<<endl; } delete res; delete stmt; delete conn; } catch (const sql::SQLException &e) { std::cerr << e.what() << '\n'; cout<<e.getErrorCode()<<endl<<e.getSQLState()<<endl<<e.getSQLStateCStr()<<endl; } cout<<get_time_now()<<",finished in "<<__FUNCTION__<<","<<__LINE__<<endl; } //main.cpp #include "model/mysqlhelper.h" void mysqlreaddemo() { mysqlhelper mh; mh.mysqlreaddemo(); } int main(int args, char **argv) { mysqlreaddemo(); }

 

 

Compile

g++ -g -std=c++2a -I. *.cpp ./model/*.cpp -o h1 -luuid -ljsoncpp -lmysqlcppconn

 

 

 

 

Run

./h1

 

 

 

 

Query from mysql table

select Idx,Id,Author,Comment,Content,Name,Title from Book;

 

 

 

标签:count,include,name,get,sql,time,now,mysqlhelper
From: https://www.cnblogs.com/Fred1987/p/16990898.html

相关文章