MySQL用C访问的示例代码

柳鲲鹏


有的朋友刚刚接触,不知道怎么用C访问。这里提供一个完整的示例代码。

#include <mysql.h>
 
#include "gh_mysql.h"
#include "gh_kit.h"
 
#define DB_TEST_QUERY       "select * from ai_task_tbl"
 
//这样能顺利取到错误。
static MYSQL    g_oDbConnection;
static MYSQL*   g_pDbConnection = NULL;
 
int db_connect(const char* server, const int port, const char* account, const char* password, const char* dbname)
{
    if (g_pDbConnection)
    {
        return 0;
    }
 
    GH_LOG_INFO("%s@%d, %s@%s, %s", server, port, account, password, dbname);
    g_pDbConnection = &g_oDbConnection;
    mysql_init(g_pDbConnection);
    if (!mysql_real_connect(g_pDbConnection, server, account, password, dbname, port, NULL, 0))
    {
        db_error();
        return -1;
    }
 
    GH_LOG_INFO("CONNECTED OK!");
 
    return 0;
}
 
int db_release()
{
    mysql_close(g_pDbConnection);
    g_pDbConnection = NULL;
    return 0;
}
 
int db_error()
{
    int error = mysql_errno(g_pDbConnection);
    if (error)
    {
        GH_LOG_INFO("ERROR! %d:%s", error, mysql_error(g_pDbConnection));
        db_release();
    }
    return error;
}
 
int db_query(const char* query)
{
    return 0;
}
 
int db_test()
{
    MYSQL_RES *sqlres;
    MYSQL_ROW sqlrow;
    MYSQL_FIELD* field;
    int num_fields;
    int counter = 0;
    char field1[32] = {0};
    char field2[32] = {0};
    int ret;
 
    if (!g_pDbConnection)
    {
        return -1;
    }
 
    ret = mysql_query(g_pDbConnection, DB_TEST_QUERY);
    if (ret)
    {
        return -1;
    }
    GH_LOG_INFO("mysql_affected_rows=%d", (int)mysql_affected_rows(g_pDbConnection));
 
    sqlres = mysql_store_result(g_pDbConnection);  
    if (!sqlres)
    {
        return -1;
    }
 
    GH_LOG_INFO("Retrieved %d rows", (int)mysql_num_rows(sqlres));
 
    num_fields = mysql_num_fields(sqlres);
    counter = 0;
    while((field = mysql_fetch_field(sqlres)))
    {
        GH_LOG_INFO("FIELD[%02d/%02d]=%s", counter, num_fields, field->name);
        if (counter == 0)
        {
            strcpy(field1, field->name);
        }
        else if (counter == 1)
        {
            strcpy(field2, field->name);
        }
 
        counter++;
    }
 
    //unsigned int mysql_field_count(MYSQL *connection);
    //MYSQL_FIELD *mysql_fetch_field(MYSQL_RES *result);
    counter = 0;
    while((sqlrow = mysql_fetch_row(sqlres)))
    {
        unsigned long *lengths;
        lengths = mysql_fetch_lengths(sqlres);
        //for(i = 0; i < num_fields && i < 10; i++)
        {
            GH_LOG_INFO("%s[%02d]=(%02d, %s), %s[%02d]=(%02d, %s)",
                field1, counter, (int) lengths[0], sqlrow[0] ? sqlrow[0] : "NULL",
                field2, counter, (int) lengths[1], sqlrow[1] ? sqlrow[1] : "NULL");
        }
 
        counter ++;
        if (counter >= 10)
        {
            break;
        }
    }
 
    mysql_free_result(sqlres);
    return 0;
}
上一篇:TIJ读书笔记03-初始化和构造器


下一篇:ABAP Netweaver和Cloud Foundry上的环境变量Environment Variable