C++ connection mysql and retrieve select sql result

1.Install mysqlconnector for c++ via executing below cmd;

sudo apt-get install libmysqlcppconn-dev

2.

#include <iostream>
#include <stdlib.h>
#include <string>
#include <mysql_connection.h>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <mysql_driver.h>
using namespace std;

void con1();

int main()
{
    con1();
    return 0;
}

void con1()
{
    sql::mysql::MySQL_Driver *driver;
    sql::Connection *con;
    sql::Statement *stmt;
    sql::ResultSet *res;

    driver = sql::mysql::get_mysql_driver_instance();
    con = driver->connect("tcp://127.0.0.1:3306", "username", "password");
    stmt = con->createStatement();

    res = stmt->executeQuery("select  host,user,plugin from mysql.user where user in ('root','fred','ms');");
    while (res->next())
    { 
        cout << "Host=" << res->getString(1);  
        cout << ",user=" << res->getString(2);
        cout << ",plugin=" << res->getString(3) << endl;
    }

    delete res;
    delete stmt;
    delete con; 
}

3.g++ compile the cpp via below command

g++ -std=c++11 -I .../include -L .../lib64 h2.cpp -lmysqlcppconn -o h2

or if you want to debug via gdb should add -g argument as below.

g++ -g -std=c++11 -I .../include -L .../lib64 h2.cpp -lmysqlcppconn -o h2

 

4.Run the compiled result

./h2

5.The result illustrated as below.

C++ connection mysql and retrieve select sql result

 

 

 Which is the same result as executed the below sql in mysql 

select  host,user,plugin from mysql.user where user in ('root','fred','ms');

C++ connection mysql and retrieve select sql result

 

原文链接: https://www.cnblogs.com/Fred1987/p/15628861.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++ connection mysql and retrieve select sql result

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/401761

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月19日 上午9:22
下一篇 2023年4月19日 上午9:22

相关推荐