Getting rows in a MySQL database table using the MySQL C and C ++ APIs

I got confused when trying to get table rows in mysql using C ++ with MySQL C API.

I can do this easily in PHP, simply because C ++ is a strongly typed language, so we also need to take care of the dirty process.

This is how I did it in PHP

  $ data = array ();
 $ i = 0;
 $ query = mysql_query ("SELECT * FROM` my_table` ");
 while ($ fetch = mysql_fetch_array ($ query))
 {
   $ data [$ i] = $ fetch ['columntobefetched'];
   $ i ++;
 } 

But how to do the same in C ++ with the MySQL API?

Here is my code so far .... with a confusing dead end ... x__x

  MYSQL * sqlhnd = mysql_init (NULL);
     mysql_real_connect (sqlhnd, "server", "user", "pass", "database", port, NULL, 0);

     mysql_query (sqlhnd, "SELECT * FROM` my_table` ");
     MYSQL_RES * confres = mysql_store_result (sqlhnd);
     int totalrows = mysql_num_rows (confres);
     int numfields = mysql_num_fields (confres);
     MYSQL_FIELD * mfield;

     while ((row = mysql_fetch_row (confres)))
     {
         for (i = 0; i <numfields; i ++)
         {
             while (mfield = mysql_fetch_field (confres))
             {
                 mfield -> // ???  I'm dead
             }
         }
     } 

Basically, I wanted to get the value from the field in the database table and store it in a variable.

Any help would be appreciated :)

thanks

+6
c ++ c api mysql
source share
2 answers

In the MySQL C API, mysql_fetch_row returns a MYSQL_ROW object, which is essentially an array of values ​​in the current row.

So your code should look something like this:

mysql_query(sqlhnd, "SELECT * FROM `my_table`"); MYSQL_RES *confres = mysql_store_result(sqlhnd); int totalrows = mysql_num_rows(confres); int numfields = mysql_num_fields(confres); MYSQL_FIELD *mfield; while((row = mysql_fetch_row(confres))) { for(i = 0; i < numfields; i++) { char *val = row[i]; // do something with val... } } 

Even better, do not do "SELECT * FROM mytable " in a program. It would be much better to name the fields that you expect so that you can be sure of the order of the returned fields.

+13
source share

If you use C ++, why not use MySQL ++ ? This is a sample code:

 mysqlpp::Connection dbconnection; dbconnection.connect("database", "server", "user", "pass"); mysqlpp::Query prepared_query = dbconnection.query( "SELECT * FROM `my_table`" ); mysqlpp::StoreQueryResult r = prepared_query.store(); int field = r.field_num("columntobefetched"); for(mysqlpp::StoreQueryResult::iterator i = r.begin(); i!=r.end();i++) { std::cout << i->at(field) << std::endl; std::cout << (*i)["columntobefetched"] << std::endl; // this will be slower } 
+4
source share

All Articles