C++ mysql_client insert into table

1.Source code in h1.cpp

#include <iostream>
#include <mysql/mysql.h>

using namespace std;

void mysqlClientInsert2();

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

void mysqlClientInsert2()
{
    try
    { 
        MYSQL *conn, mysql;
        int state;

        mysql_init(&mysql);
        conn = mysql_real_connect(&mysql, "localhost", "root", "Root0001!", "myDB", 0, 0, 0);

        if (conn == NULL)
        {
            cout << mysql_error(&mysql) << endl;
            return;
        }

        string str = "Insert into mt(BookId,BookName,BookTitle) values(1,'C++','C++ Programming Books!')";
        state=mysql_query(conn, str.c_str());
        cout<<"State ="<<state<<endl;
    }
    catch (const std::exception &e)
    {
        std::cerr << e.what() << '\n';
    }
}

 

2.Compile via c++ as below command

g++ -g -std=c++2a -I. -Wall -I/usr/include/mysql/ *.cpp -o h1 -L/usr/lib -lmysqlclient;

3.Execute

./h1 -1;

4.Result

 

posted @ 2022-05-15 22:59  FredGrit  阅读(33)  评论(0编辑  收藏  举报