1. 程式人生 > >C語言連線Mariadb示例(Centos7.6環境)

C語言連線Mariadb示例(Centos7.6環境)

示例程式碼如下

#include <stdio.h>
#include <stdlib.h>
#include <mysql/mysql.h>

int main(int argc,char *argv[])
{
    int num_fields,i;
    MYSQL_RES *res;
    MYSQL_ROW row;
    MYSQL_FIELD *field;
    /*建立資料連線物件*/
    MYSQL *con = mysql_init(NULL);
    if(con == NULL)
    {
        fprintf(stderr, "%s\n", mysql_error(con));
        exit(EXIT_FAILURE);
    }
    if(!mysql_real_connect(con, "localhost", "root", "haodangqiankun", NULL, 0, NULL,0))
    {
        fprintf(stderr, "%s\n", mysql_error(con));
        mysql_close(con);
        exit(EXIT_FAILURE);
    }
    if(mysql_query(con, "show databases;"))
    {
        fprintf(stderr, "%s\n", mysql_error(con));
        mysql_close(con);
        exit(EXIT_FAILURE);
    }
    res=mysql_store_result(con);
    num_fields= mysql_num_fields(res);
    field=mysql_fetch_fields(res);
    while (row = mysql_fetch_row(res)) //獲取整條資料內容
    {
        for(i=0;i<num_fields;++i)
        {
            printf("[%s]=>[%s]\n",field[i].name,row[i]);
        }  
    }
    mysql_free_result(res);
    puts("mariadb is connect and run succesed!");
    mysql_close(con);
    return 0;
}

完整編譯連線命令如下

gcc testdb.c -o mdb.o -lmariadbclient -lpthread -lm -ldl -lssl -lcryp