使用C API操作mysql数据库

来源:互联网 发布:淘宝联盟的返利 编辑:程序博客网 时间:2024/05/21 14:53
使用C API操作mysql数据库
转自:http://blog.csdn.net/lyjinger/article/details/1648898
说明:使用mysql提供的C API编程实现数据库的最基本操作,算是抛砖引玉吧。如果想了解更多,请安装mysql(如何安装可以参考本人的“软件使用之:mysql服务器安装和配置”)并仔细阅读其操作手册。
例子代码下载地址:
  http://pickup.mofile.com/3413396272029309

一、基本操作步骤:   
1、初始化mysql
  MYSQL *mysql = mysql_init(NULL);
2、连接数据库
  mysql_real_connect(mysql, HOST, USER, PASSWORD, DATABASE, 0, NULL, 0);
3、执行数据库操作
  mysql_query(mysql, sql);
4、关闭mysql
  mysql_close(mysql);

二、执行查询操作:
  相信没有人会否认查询是数据库中最基本、最常用的操作吧,呵呵。
mysql查询需要在调用mysql_query()后执行其它函数来获取数据库表中相应字段的值:
1、存储操作结果集
  MYSQL_RES *mysql_res = mysql_store_result(mysql);
2、获取结果集中一行记录
  MYSQL_ROW *mysql_row = mysql_fetch_row(mysql_res);
3、通过指针获取记录中的值
  指针mysql_row[0]指向的就是该条记录第一列(查询的第一个字段)的值
4、释放存储结果集
  mysql_free_result(mysql_res);

三、其它操作:
1、设置查询返回数据的字符集
  #define MYSQL_CHARSET    "gbk" /* 替换为你想使用的字符集 */
  char sql[1024] = {0};
  sprintf(sql, "set names %s", MYSQL_CHARSET);
  mysql_query(mysql, sql);
2、获取结果集中列(查询表的字段)的数目
  int num_fields = mysql_num_fields(mysql_res);

四、相关函数说明:
1、初始化函数:用于分配或初始化一个MYSQL对象,返回其句柄。
MYSQL *mysql_init(MYSQL *mysql)

Description

Allocates or initializes a MYSQL object suitable for mysql_real_connect(). If mysql is a NULL pointer, the function allocates, initializes, and returns a new object. Otherwise, the object is initialized and the address of the object is returned. If mysql_init() allocates a new object, it is freed when mysql_close() is called to close the connection.

Return Values

An initialized MYSQL* handle. NULL if there was insufficient memory to allocate a new object.

2、关闭函数:用于关闭数据库连接,释放前面分配的MYSQL对象资源。
void mysql_close(MYSQL *mysql)

Description

Closes a previously opened connection. mysql_close() also deallocates the connection handle pointed to by mysql if the handle was allocated automatically by mysql_init() or mysql_connect().

Return Values

None.

3、连接数据库函数:通过指定主机名(或IP)、用户、密码、要操作的数据库来连接mysql服务器。
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)

Description

mysql_real_connect() attempts to establish a connection to a MySQL database engine running on host. mysql_real_connect() must complete successfully before you can execute any other API functions that require a valid MYSQL connection handle structure.

Return Values

A MYSQL* connection handle if the connection was successful, NULL if the connection was unsuccessful. For a successful connection, the return value is the same as the value of the first parameter.

4、SQL语句执行函数:用于执行SQL语句,对数据库的操作由此函数完成。
int mysql_query(MYSQL *mysql, const char *stmt_str)

Description

Executes the SQL statement pointed to by the null-terminated string stmt_str. Normally, the string must consist of a single SQL statement and you should not add a terminating semicolon (‘;’) or /g to the statement. If multiple-statement execution has been enabled, the string can contain several statements separated by semicolons. See Section 22.2.9, “C API Handling of Multiple Statement Execution”.

mysql_query() cannot be used for statements that contain binary data; you must use mysql_real_query() instead. (Binary data may contain the ‘/0’ character, which mysql_query() interprets as the end of the statement string.)

Return Values

Zero if the statement was successful. Non-zero if an error occurred.

5、存储结果集函数:存储sql语句成功返回的结果
MYSQL_RES *mysql_store_result(MYSQL *mysql)

Description

After invoking mysql_query() or mysql_real_query(), you must call mysql_store_result() or mysql_use_result() for every statement that successfully retrieves data (SELECT, SHOW, DESCRIBE, EXPLAIN, CHECK TABLE, and so forth). You must also call mysql_free_result() after you are done with the result set.

Return Values

A MYSQL_RES result structure with the results. NULL (0) if an error occurred.

6、获取记录函数:从结果集result中返回一条记录
MYSQL_ROW mysql_fetch_row(MYSQL_RES *result)

Description

Retrieves the next row of a result set. When used after mysql_store_result(), mysql_fetch_row() returns NULL when there are no more rows to retrieve. When used after mysql_use_result(), mysql_fetch_row() returns NULL when there are no more rows to retrieve or if an error occurred.

The number of values in the row is given by mysql_num_fields(result). If row holds the return value from a call to mysql_fetch_row(), pointers to the values are accessed as row[0] to row[mysql_num_fields(result)-1]. NULL values in the row are indicated by NULL pointers.

The lengths of the field values in the row may be obtained by calling mysql_fetch_lengths(). Empty fields and fields containing NULL both have length 0; you can distinguish these by checking the pointer for the field value. If the pointer is NULL, the field is NULL; otherwise, the field is empty.

Return Values

A MYSQL_ROW structure for the next row. NULL if there are no more rows to retrieve or if an error occurred.

7、释放存储的结果集函数:释放存储结果所分配的资源
void mysql_free_result(MYSQL_RES *result)

Description

Frees the memory allocated for a result set by mysql_store_result(), mysql_use_result(), mysql_list_dbs(), and so forth. When you are done with a result set, you must free the memory it uses by calling mysql_free_result().

Return Values

None.

8、获取结果集的列数:
unsigned int mysql_num_fields(MYSQL_RES *result)

To pass a MYSQL* argument instead, use unsigned int mysql_field_count(MYSQL *mysql).

Description

Returns the number of columns in a result set.

Return Values

An unsigned integer representing the number of columns in a result set.

9、获取当前记录各字段值的长度:
unsigned long *mysql_fetch_lengths(MYSQL_RES *result)

Description

Returns the lengths of the columns of the current row within a result set. If you plan to copy field values, this length information is also useful for optimization, because you can avoid calling strlen(). In addition, if the result set contains binary data, you must use this function to determine the size of the data, because strlen() returns incorrect results for any field containing null characters.

The length for empty columns and for columns containing NULL values is zero. To see how to distinguish these two cases, see the description for mysql_fetch_row().

Return Values

An array of unsigned long integers representing the size of each column (not including any terminating null characters). NULL if an error occurred.

五、代码编译和链接:
1、编译选项:
添加mysql头文件目录
  -I/usr/local/mysql/include # 通过二进制包安装的
  -I/usr/local/mysql/include/mysql # 通过源代码包安装的
添加mysql库文件目录
  -L/usr/local/mysql/lib # 通过二进制包安装的
  -L/usr/local/mysql/lib/mysql # 通过源代码包安装的
2、链接选项(分动态链接和静态链接来讲)
动态链接
  -lmysqlclient -lm -lz
静态链接
  -static -lmysqlclient -lmygcc -lm -lz -lcrypt -lpthread

  顺便说说mysql的静态链接,我首先使用的用动态链接:-lmysqlclient -lm -lz顺利通过,export LD_LIBRARY_PATH=/usr/local/mysql/lib后执行成功。接着我是用静态链接:-static -lmysqlclient -lm -lz,出来一堆链接错误,基本分为:
  undefined reference to `__pure_virtual'
  undefined reference to `__builtin_delete'

  undefined reference to `pthread_self'
其中:pthread_self好办,肯定是加载pthread线程库,而pure_virtual和builtin_delete不熟,到网上查了下,没找到解决方法,倒是留意到有个人说了句二者是c++里的,于是开始怀疑是不是编译器的问题,到/usr/local/mysql/lib下找了下,发现一个库,名叫:libmygcc.a,想想是不是链接这个库就可以了呢?试一下,-static -lmysqlclient -lmygcc -lm -lz -lcrypt -lpthread,成功!呵呵,顺利完成任务!
  所以,有时候做事还是要自己多动动脑筋,多想想点子,多动动手的。
原创粉丝点击