//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 mysqlSelectLimitPage(int interval); }; #endif //Util.cpp #include "Model/Util.h" void Util::mysqlSelectLimitPage(int interval) { try { sql::Driver *dvr; sql::Connection *conn; sql::Statement *stmt; sql::ResultSet *res; sql::PreparedStatement *pStmt; dvr = get_driver_instance(); conn = dvr->connect("tcp://127.0.0.1:3306", "root", "password); conn->setSchema("db"); stmt = conn->createStatement(); res = stmt->executeQuery("select count(*) from Book;"); int rowsCount = -1; while (res->next()) { rowsCount = res->getInt(1); cout << "rowsCount=" << rowsCount << endl; } int startIndex = 0; int loops = rowsCount / interval; int remainder = rowsCount % interval; stringstream sqlSS; for (int i = 0; i <= loops+1; i++) { sqlSS << "select Idx from Book limit "; sqlSS << startIndex << "," << interval << ";" << endl; res = stmt->executeQuery(sqlSS.str()); if (res->rowsCount() > 0) { cout << endl << "SQL=" << sqlSS.str(); while (res->next()) { cout << res->getInt(1) << "\t"; } cout << endl << "Loop=" << i << endl; startIndex += interval; sqlSS = stringstream(); } } delete res; delete stmt; delete conn; } catch (sql::SQLException &e) { std::cerr << e.what() << '\n'; cout << e.getErrorCode() << endl; cout << e.getSQLState() << endl; } }
//main.cpp #include "Model/Util.h" void mysqlLimitPage28(int interval); int main(int args, char **argv) { mysqlLimitPage28(atoi(argv[1])); } void mysqlLimitPage28(int interval) { Util ul; ul.mysqlSelectLimitPage(interval); }
Compile
g++ -std=c++2a -I. *.cpp ./Model/*.cpp -o h1 -luuid -lpthread -lmysqlcppconn;
Execute
./h1 100;
Make a summary,coding in for loop and the startIndex should incremente by interval,the interval is fixed.
select Idx from Book limit startIndex,interval;
the startIndex=startIndex+interval;