Search code examples
c++mysqlsqlotl

Insert data into mysql table from c++ program using OTL library


I want to insert int and string value into mysql table from c++ program.

for (std::map < int, std::vector < std::string > >::iterator hit = three_highest.begin(); hit != three_highest.end(); ++hit) {
    //std::cout << hit->first << ":";

    for (std::vector < std::string >::iterator vit = (*hit).second.begin(); vit != (*hit).second.end(); vit++) {
        std::cout << hit->first << ":";
        std::cout << *vit << "\n";

I want to insert hit->first and *vit.

  1. I saw example here : OTL Example for mysql. Will it work for me?

    And how to set OTL environment in my system? Do I need to install it or what?

  2. Here is very simple example in another way. But it directly include <mysql.h> Which I could not find in my system. What environment it using?

I am using Linux - Ubuntu environment.


Solution

  • Here I got how to connect c++ with mysql:

    first compiled the c++ connector library from source but after a while I thought maybe I did something wrong so I then just used apt to get it with:

    sudo apt-get install  libmysqlcppconn-dev
    

    So I have now had this problem for a week now and I became very frustrated with it as well. I just now was able to finally build a program that does nothing except login to mysql and I literally squealed with joy. Here is what I have and I hope it helps.

    I first compiled the c++ connector library from source but after a while I thought maybe I did something wrong so I then just used apt to get it with:

    sudo apt-get install libmysqlcppconn-dev

    And here is my simple tester source file "tester.cpp"

    #include <stdlib.h>
    #include <iostream>
    #include <mysql_connection.h>
    #include <driver.h>
    #include <exception.h>
    #include <resultset.h>
    #include <statement.h>
    
    using namespace sql;
    int main(void){
      sql::Driver *driver;
      sql::Connection *con;
    
      driver = get_driver_instance();
      con = driver->connect("tcp://127.0.0.1:3306","root","YOURPASSWORD");
    
      return 0;
    }
    

    And finally g++ compile command:

    sudo g++ -Wall -I/usr/include/cppconn -o testapp tester.cpp -L/usr/lib -lmysqlcppconn