C++ mysql print all rows all columns data in Ubuntu

1.Install mysql connector

sudo apt-get install libmysqlcppconn-dev

 

 

 2.Program 

//Util.h
#ifndef Util_H
#define Util_H
#include <chrono>
#include <ctime>
#include <fstream> 
#include <functional>
#include <future>
#include <iostream>
#include <random>
#include <sstream>
#include <thread>
#include <unistd.h>
#include <uuid/uuid.h>
#include <vector>
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/resultset.h>
#include <cppconn/exception.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
  

using namespace std;

class Util
{
    public: 
    void connectToMySQL();
};
#endif

//Util.cpp
void Util::connectToMySQL()
{
    try
    {
        sql::Driver *dvr;
        sql::Connection *conn;
        sql::Statement *stmt;
        sql::ResultSet *res;
        sql::ResultSetMetaData *resMeta;

        dvr=get_driver_instance();
        conn=dvr->connect("tcp://127.0.0.1:3306","root","password");
        conn->setSchema("mysql");
        stmt=conn->createStatement();
        res=stmt->executeQuery("select * from user;");
        resMeta=res->getMetaData();

        int columnsCoumt=resMeta->getColumnCount();
        cout<<"ColumnsCount="<<columnsCoumt<<endl;

        while(res->next())
        {
            for(int i=1;i<=columnsCoumt;i++)
            {
                cout<<res->getString(i)<<"\t";
            }
            cout<<endl;
        }
            
        delete res;
        delete stmt;
        delete conn;
    }
    catch(sql::SQLException &e)
    {
        std::cerr << e.what() << '\n';
        cout<<"FILE:"<<__FILE__<<",FUNCTION:"<<__FUNCTION__<<",LINE:"<<__LINE__<<endl;
        cout<<"Code:"<<e.getErrorCode()<<endl;
        cout<<"State:"<<e.getSQLState()<<endl;
    }
    
}

 

3.Call the method in main method

 

//main.cpp

#include "Model/Util.h"
void mysqlConnector27();

int main(int args, char **argv)
{
    mysqlConnector27();
}

void mysqlConnector27()
{
    Util ul;
    ul.connectToMySQL();
}

 

4.Compile via g++

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

5.Run the compiled result

./h1

 

 

 

When traverse the ResultSet getting by statement exeuctequery("select * from user") method

 

Pay more attention to the method of get columns count via 

 
sql::ResultSetMetaData *resMeta;
resMeta=res->getMetaData();
int columnsCoumt=resMeta->getColumnCount();
cout<<"ColumnsCount="<<columnsCoumt<<endl;

 

 
And be cautious that the column index in resultset started from 1 instead of 0,so when loop the columns,the initial column index is 1 instead of 0;
cout<<"ColumnsCount="<<columnsCoumt<<endl;
        while(res->next())
        {
       //The column index begins with 1 not 0
for(int i=1;i<=columnsCoumt;i++) { cout<<res->getString(i)<<"\t"; } cout<<endl; }

 

 

posted @ 2022-07-02 21:08  FredGrit  阅读(35)  评论(0编辑  收藏  举报