wiki:db/mysql/MySQLExample01
Last modified 12 years ago Last modified on 04/18/2007 10:15:25 PM

Example how to get mysql field type

Create table:

create table types(_tinyint tinyint, _smallint smallint, _mediumint mediumint, _int int, _bigint bigint)

Build this:

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

int main(int, char**) {
    MYSQL mysql;
    mysql_init(&mysql);
    
    assert(mysql_real_connect(&mysql,"localhost","becla","","test",0,0,0));
    assert(!mysql_query(&mysql, "SELECT * FROM test.types LIMIT 1"));

    MYSQL_RES *result = mysql_store_result(&mysql);
    assert(result);

    MYSQL_FIELD *fields = mysql_fetch_fields(result);
    assert(fields);

    unsigned int num_fields = mysql_num_fields(result);
    for(int i = 0; i < num_fields; i++){
        std::cout << "Type of " << fields[i].name
                  << " is: "  << fields[i].type << std::endl;
    } 
    mysql_close(&mysql);

    std::cout << "MySQL type numbers:
"
              << "  MYSQL_TYPE_SHORT     = " << MYSQL_TYPE_SHORT << "
"
              << "  MYSQL_TYPE_LONG      = " << MYSQL_TYPE_LONG  << "
"
              << "  MYSQL_TYPE_LONGLONG  = " << MYSQL_TYPE_LONGLONG << "
"
              << "  MYSQL_TYPE_INT24     = " << MYSQL_TYPE_INT24 << std::endl;

    return 0;
}

Of course, replace host name, user name and password. I used:

g++ -g testmysql.c -lmysqlclient -L/usr/lib -o testmysql

Output I am getting:

Type of _tinyint is: 1
Type of _smallint is: 2
Type of _mediumint is: 9
Type of _int is: 3
Type of _bigint is: 8
MySQL type numbers:
  MYSQL_TYPE_SHORT     = 2
  MYSQL_TYPE_LONG      = 3
  MYSQL_TYPE_LONGLONG  = 8
  MYSQL_TYPE_INT24     = 9

BTW, these types are defined in mysql_com.h. Relevant url: http://dev.mysql.com/doc/internals/en/field-packet.html