执行SQL语句的增、删、改、查的主要API函数为:
int mysql_query(MYSQL *connection, const char *query);
函数接收参数连接句柄和字符串形式的有效SQL语句(没有结束的分号,这与mysql工具不同)。如果成功,它返回0。
如果包含二进制数据的查询,要使用mysql_real_query.
检查受查询影响的行数:
my_ulonglong mysql_affected_rows(MYSQL *connection);
my_ulonglong是无符号长整形,为%lu格式
这个函数返回受之前执行update,insert或delete查询影响的行数。
例子
数据库中有一个student表
CREATE TABLE student (
student_no varchar(12) NOT NULL PRIMARY KEY,
student_name varchar(12) NOT NULL
);
增、删、改代码:
#include
#include
#include
#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); // 注意取地址符&
if (mysql_real_connect(&conn, host, user, password, database, 0, NULL, 0)) {
printf("Connection success!\n");
} else {
fprintf(stderr, "Connection failed!\n");
if (mysql_errno(&conn)) {
fprintf(stderr, "Connection error %d: %s\n", mysql_errno(&conn), mysql_error(&conn));
}
exit(EXIT_FAILURE);
}
}
void insert() {
int res = mysql_query(&conn, "INSERT INTO student(student_no,student_name) VALUES('123465', 'Ann')");
if (!res) {
printf("Inserted %lu rows\n", (unsigned long)mysql_affected_rows(&conn));
} else {
fprintf(stderr, "Insert error %d: %s\n", mysql_errno(&conn), mysql_error(&conn));
}
}
void update() {
int res = mysql_query(&conn, "UPDATE student SET student_name='Anna' WHERE student_no='123465'");
if (!res) {
printf("Update %lu rows\n", (unsigned long)mysql_affected_rows(&conn));
} else {
fprintf(stderr, "Update error %d: %s\n", mysql_errno(&conn), mysql_error(&conn));
}
}
void delete() {
int res = mysql_query(&conn, "DELETE from student WHERE student_no='123465'");
if (!res) {
printf("Delete %lu rows\n", (unsigned long)mysql_affected_rows(&conn));
} else {
fprintf(stderr, "Delete error %d: %s\n", mysql_errno(&conn), mysql_error(&conn));
}
}
int main (int argc, char *argv[]) {
connection("localhost", "root", "shuang", "shuangde");
delete();
mysql_close(&conn);
exit(EXIT_SUCCESS);
}
返回数据的语句: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
// 相关函数:
// 这是在成功调用mysql_query之后使用此函数,这个函数将立刻保存在客户端中返回的所有数据。它返回一个指向结果集结构的指针,如果失败返回NULL
MYSQL_RES *mysql_store_result(MYSQL *connection);
// 这个函数接受由mysql_store_result返回的结果结构集,并返回结构集中的行数
my_ulonglong mysql_num_rows(MYSQL_RES *result);
// 这个函数从使用mysql_store_result得到的结果结构中提取一行,并把它放到一个行结构中。当数据用完或发生错误时返回NULL.
MYSQL_ROW mysql_fetch_row(MYSQL_RES *resutl);
// 这个函数用来在结果集中跳转,设置将会被下一个mysql_fetch_row操作返回的行。参数offset是一个行号,它必须是在0~结果总行数-1的范围内。传递
// 0将会导致下一个mysql_fetch_row调用返回结果集中的第一行。
void mysql_data_seek(MYSQL_RES *result, my_ulonglong offset);
// 返回一个偏移值,它用来表示结果集中的当前位置。它不是行号,不能把它用于mysql_data_seek
MYSQL_ROW_OFFSET mysql_row_tell(MYSQL_RES *result);
// 这将在结果集中移动当前的位置,并返回之前的位置
MYSQL_ROW_OFFSET mysql_row_seek(MYSQL_