MySQL C API


1.头文件,API包含在mysqlclient库中

#include <mysql.h>

在编译时,要加上-lmysqlclient

2.创建变量MYSQL mysql

MYSQL结构代表1个数据库连接句柄,几乎所有的MySQL函数都会使用到,其结构体如下:

typedef struct st_mysql {
  NET           net;            /* Communication parameters */
  gptr          connector_fd;   /* ConnectorFd for SSL */
  char          *host,*user,*passwd,*unix_socket,
                *server_version,*host_info,*info,*db;
  unsigned int  port,client_flag,server_capabilities;
  unsigned int  protocol_version;
  unsigned int  field_count;
  unsigned int  server_status;
  unsigned long thread_id;      /* Id for connection in server */
  my_ulonglong affected_rows;
  my_ulonglong insert_id;       /* id if insert on table with NEXTNR */
  my_ulonglong extra_info;              /* Used by mysqlshow */
  unsigned long packet_length;
  enum mysql_status status;
  MYSQL_FIELD   *fields;
  MEM_ROOT      field_alloc;
  my_bool       free_me;        /* If free in mysql_close */
  my_bool       reconnect;      /* set to 1 if automatic reconnect */
  struct st_mysql_options options;
  char          scramble_buff[9];
  struct charset_info_st *charset;
  unsigned int  server_language;
} MYSQL;

3.初始化mysql变量,调用mysql_init(&mysql),并调用mysql_real_connect()连接数据库,其函数原型如下:

MYSQL *mysql_real_connect(MYSQL *mysql, const char *host, const char *user, const char *passwd, const char *db, unsigned int port, const char *unix_socket, unsigned long client_flag)

4.构建sql语句并进行查询:mysql_real_query,函数原型:

int mysql_real_query(MYSQL *mysql, const char *query, unsigned long length)

5.声明一个MYSQL_RES类型的变量:MYSQL_RES res,结构体如下:

typedef struct st_mysql_res {
  my_ulonglong row_count;
  unsigned int  field_count, current_field;
  MYSQL_FIELD   *fields;
  MYSQL_DATA    *data;
  MYSQL_ROWS    *data_cursor;
  MEM_ROOT      field_alloc;
  MYSQL_ROW     row;            /* If unbuffered read */
  MYSQL_ROW     current_row;    /* buffer to current row */
  unsigned long *lengths;       /* column lengths of current row */
  MYSQL         *handle;        /* for unbuffered reads */
  my_bool       eof;            /* Used my mysql_fetch_row */
} MYSQL_RES;
然后将查询结果存储到MYSQL_RES中:
res = mysql_store_result(&mysql);
函数原型:

MYSQL_RES *mysql_store_result(MYSQL *mysql)

如果查询未返回结果集,mysql_store_result()将返回Null指针(例如,如果查询是INSERT语句)。

如果读取结果集失败,mysql_store_result()还会返回Null指针。通过检查mysql_error()是否返回非空字符串,mysql_errno()是否返回非0值,或mysql_field_count()是否返回0,可以检查是否出现了错误。

如果未返回行,将返回空的结果集。(空结果集设置不同于作为返回值的空指针)。

6.一旦调用了mysql_store_result()并获得了不是Null指针的结果,调用mysql_num_rows()来找出结果集中的行数,调用mysql_fetch_row()来获取结果集中的行,或调用mysql_row_seek()和mysql_row_tell()来获取或设置结果集中的当前行位置

7.调用mysql_free_result()释放结果集

8. 通过调用mysql_close(),关闭与MySQL服务器的连接

相关内容