在介绍mysql c api的一些常用参数前,有必要先学习一下对应的数据结构。
数据结构
MYSQL
连接数据库前,必须先创建MYSQL变量,此变量在很多Mysql API函数会用到。它包含了一些连接信息等数据。
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;
MYSQL_RES
MYSQL_RES结构体中包含了查询结果集,也就是从数据库中查询到的数据。可以使用mysql_store_result或mysql_use_result函数获得。这个结构代表返回行的一个查询的(SELECT, SHOW, DESCRIBE, EXPLAIN)的结果。返回的数据称为“数据集”,在C的API里对应的就是MYSQL_RES,从数据库读取数据,最后就是从MYSQL_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_ROW
这是一个行数据的类型安全(type-safe)的表示。当前它实现为一个计数字节的字符串数组。(如果字段值可能包含二进制数据,你不能将这些视为空终止串,因为这样的值可以在内部包含空字节) 行通过调用mysql_fetch_row()获得。
typedef char **MYSQL_ROW;
MYSQL_FIELD
MYSQL_FIELD中包含了字段名、字段类型和大小等信息。可以重复调用mysql_fetch_field函数获得所有字段的信息。可以通过重复调用mysql_fetch_field()对每一列获得MYSQL_FIELD结构。字段值不是这个结构的部分;它们被包含在一个MYSQL_ROW结构中。
typedef struct st_mysql_field {
char *name; /* Name of column */
char *table; /* Table of column if column was a field */
char *def; /* Default value (set by mysql_list_fields) */
enum enum_field_types type; /* Type of field. Se mysql_com.h for types */
unsigned int length; /* Width of column */
unsigned int max_length; /* Max width of selected set */
unsigned int flags; /* Div flags */
unsigned int decimals; /* Number of decimals in field */
} MYSQL_FIELD;
c api使用步骤
1、首先要包含mysql的头文件,并链接mysql动态库。
#include <mysql.h>
2、创建MYSQL变量。如:
MYSQL mysql;
3、初始化MYSQL变量。
mysql_init(&mysql);
4、调用mysql_real_connect函数连接Mysql数据库。
MYSQL * STDCALL 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 clientflag);
参数说明:
mysql:前面定义的MYSQL变量;
host:MYSQL服务器的地址;
user:登录用户名;
passwd:登录密码;
db:要连接的数据库;
port:MYSQL服务器的TCP服务端口;
unix_socket:unix连接方式,为NULL时表示不使用socket或管道机制;
clientflag:Mysql运行为ODBC数据库的标记,一般取0。
连接失败时该函数返回0。
5、调用mysql_real_query函数进行数据库查询。
int STDCALL mysql_real_query(MYSQL *mysql,
const char *q,
unsigned long length);
参数说明:
mysql:前面定义的MYSQL变量;
q:SQL查询语句;
length:查询语句的长度。
查询成功则该函数返回0。
6、通过调用mysql_store_result或mysql_use_result函数返回的MYSQL_RES变量获取查询结果数据。
两个函数的原型分别为:
MYSQL_RES * STDCALL mysql_store_result(MYSQL *mysql);
MYSQL_RES * STDCALL mysql_use_result(MYSQL *mysql);
这两个函数分别代表了获取查询结果的两种方式。
第一种,调用mysql_store_result函数将从Mysql服务器查询的所有数据都存储到客户端,然后读取;
第二种,调用mysql_use_result初始化检索,以便于后面一行一行的读取结果集,而它本身并没有从服务器读取任何数据,这种方式较之第一种速度更快且所需内存更少,但它会绑定服务器,阻止其他线程更新任何表,而且必须重复执行mysql_fetch_row读取数据,直至返回NULL,否则未读取的行会在下一次查询时作为结果的一部分返回,故经常我们使用mysql_store_result。
7、调用mysql_fetch_row函数读取结果集数据。
上述两种方式最后都是重复调用mysql_fetch_row函数读取数据。
MYSQL_ROW STDCALL mysql_fetch_row(MYSQL_RES *result);
参数result就是mysql_store_result或mysql_use_result的返回值。
该函数返回MYSQL_ROW型的变量,即字符串数组,假设为row,则row[i]为第i个字段的值。当到结果集尾部时,此函数返回NULL。
8、结果集用完后,调用mysql_free_result函数释放结果集,以防内存泄露。
void STDCALL mysql_free_result(MYSQL_RES *result);
9、不再查询Mysql数据库时,调用mysql_close函数关闭数据库连接。
void STDCALL mysql_close(MYSQL *sock);
简单例子
#include <mysql.h>
#include <stdio.h>
int main()
{
MYSQL mysql; // need a instance to init
MYSQL_RES *res;
MYSQL_ROW row;
char *query;
int t,r;
// connect the database
mysql_init(&mysql);
if (!mysql_real_connect(&mysql,
”localhost”,
“mmim”,
“mmim”,
“test”,
0,
NULL,
0)) {
printf( “Error connecting to database: %s\n”,mysql_error(&mysql));
} else
printf(“Connected…\n”);
// get the result from the executing select query
query = “select * from t1″;
t = mysql_real_query(&mysql, query, (unsigned int) strlen(query));
if (t) {
printf(“Error making query: %s\n”,
mysql_error(&mysql));
} else
printf(“[%s] made…\n”, query);
res = mysql_store_result(&mysql);
while(row = mysql_fetch_row(res)) {
for(t=0; t < mysql_num_fields(res); t++) {
printf(“%s “,row[t]);
}
printf(“\n”);
}
mysql_free_result(res); //free result after you get the result
sleep(1);
// execute the insert query
query = “insert into t1(id, name) values(3, ‘kunp’)”;
t = mysql_real_query(&mysql,query,(unsigned int) strlen(query));
if (t) {
printf(“Error making query: %s\n”,
mysql_error(&mysql));
}
else
printf(“[%s] made…\n”, query);
mysql_close(&mysql);
return 0;
}
假定mysql的头文件在/usr/include/mysql,库文件在/usr/lib/mysql,执行下列命令进行编译:
gcc testsql.c -I/usr/include/mysql -L/usr/lib/mysql -lmysqlclient
参考:
http://ourmysql.com/archives/413
http://blog.51cto.com/a1liujin/1686202