bitsCN.com
执行SQL语句的增、删、改、查的主要API函数为:
1 | int mysql_query(MYSQL *connection, const char *query);
|
登入後複製
函数接收参数连接句柄和字符串形式的有效SQL语句(没有结束的分号,这与mysql工具不同)。如果成功,它返回0。
如果包含二进制数据的查询,要使用mysql_real_query.
检查受查询影响的行数:
1 | my_ulonglong mysql_affected_rows(MYSQL *connection);
|
登入後複製
my_ulonglong是无符号长整形,为%lu格式
这个函数返回受之前执行update,insert或delete查询影响的行数。
例子
数据库中有一个student表
1 | CREATE TABLE student ( student_no varchar(12) NOT NULL PRIMARY KEY, student_name varchar(12) NOT NULL );
|
登入後複製

增、删、改代码:
1 | # include <stdio.h># include <stdlib.h># include <string.h># include "mysql.h" # include "errmsg.h" # include "mysqld_error.h" MYSQL conn;void connection( const char* host, const char* user, const char* password, const char* database) { mysql_init(&conn);
|
登入後複製
返回数据的语句:select
SQL最常见的用法是提取数据而不是插入或更新数据。数据是用select语句提取的
C应用程序提取数据一般需要4个步骤:
1、执行查询
2、提取数据
3、处理数据
4、必要的清理工作
就像之前的insert和update一样,使用mysql_query来发送SQL语句,然后使用mysql_store_result或mysql_use_result来提取数据,具体使用哪个语句取决于你想如何提取数据。接着,将使用一系列mysql_fetch_row来处理数据。最后,使用mysql_free_result释放查询占用的内存资源。
一次提取所有数据:mysql_store_result
示例代码:
1 | # include <stdio.h># include <stdlib.h># include <string.h># include "mysql.h" # include "errmsg.h" # include "mysqld_error.h" MYSQL conn;MYSQL_RES *res_ptr;MYSQL_ROW sqlrow;void connection( const char* host, const char* user, const char* password, const char* database) { mysql_init(&conn);
|
登入後複製
一次提取一行数据:mysql_use_result
使用方法和mysql_store_result完全一样,把上面代码的mysql_store_result改为mysql_use_result即可。
mysql_use_result具备资源管理方面的实质性好处,更好地平衡了网络负载,以及减少了可能非常大的数据带来的存储开销,但是不能与mysql_data_seek、mysql_row_seek、mysql_row_tell、mysql_num_rows一起使用。如果数据比较少,用mysql_store_result更好。
处理返回的数据
代码示例:
1 | # include <stdio.h># include <stdlib.h># include <string.h># include "mysql.h" # include "errmsg.h" # include "mysqld_error.h" MYSQL conn;MYSQL_RES *res_ptr;MYSQL_ROW sqlrow;void connection( const char* host, const char* user, const char* password, const char* database) { mysql_init(&conn);
|
登入後複製
bitsCN.com