一.基本函数及介绍
1.初始化数据库连接的实例对象
MYSQL* mysql = mysql_init(NULL);
2.连接数据库服务器
mysql_real_connect(数据库操作句柄,主机地址,用户名,用户密码,数据库名称,端口号,套接字/管道描述符,标志位);
示例: mysql_real_connect(mysql,"127.0.0.1","root",NULL,"image_server",0,NULL,0);
返回值为空则表示出错
3.设置字符集
mysql_set_character_set(mysql,"utf8");
返回值不为0 则表示出错
4.执行SQL语句: 执行语句,获取结果集,获取条数列数,遍历结果,释放结果集
mysql_query(mysql,sql语句);
返回值不为0则表示出错
MYSQL_RES* res = mysql_store_result(mysql); //获取结果集
//返回值为空则表示出错
int num_row = mysql_num_rows(res);
int num_col = mysql_num_fields(res);
MYSQL_ROW row = mysql_fetch_row(res); //获取当前行的信息
5.关闭数据库操作句柄
mysql_close(mysql);
二.具体应用
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <mysql/mysql.h>
int main(){
//1.初始化句柄
MYSQL *mysql = mysql_init(NULL);
if(mysql == NULL){
printf("mysql init error\n");
return -1;
}
//2.连接服务器
//mysql_real_connect(操作句柄,主机地址,用户名,密码,库名称,端口号,套接字,标志位);
if(mysql_real_connect(mysql,"127.0.0.1","root",NULL,"image_server",0,NULL,0) == NULL){
printf("connect mysql server failed:%s",mysql_error(mysql));
mysql_close(mysql);
return -1;
}
//3.选择数据库
//4.设置字符集
if(mysql_set_character_set(mysql,"utf8") != 0){
printf("set character failed:%s",mysql_error(mysql));
mysql_close(mysql);
return -1;
}
//5.执行SQL语句 : 执行语句,获取结果集,获取条数列数,遍历结果,释放结果集
//char* insert_sql = "insert table_image values(4,'电智4',2018,'./image/44.jpg','/image/44.jpg','deowjddjkadjadddfd',now());";
//char* update_sql = "update table_image set name='电智4' where id = 4;";
//char* delete_sql = "delete from table_image where id=4;";
char* select_sql = "select * from table_image";
if(mysql_query(mysql,select_sql) != 0){
printf("mysql query faild:%s",mysql_error(mysql));
mysql_close(mysql);
return -1;
}
//获取结果集
MYSQL_RES* res = mysql_store_result(mysql);
if(res == NULL){
printf("store result failed:%s",mysql_error(mysql));
mysql_close(mysql);
return -1;
}
int num_row = mysql_num_rows(res);
int num_col = mysql_num_fields(res);
int i,j;
for(i = 0;i < num_row;i++){
MYSQL_ROW row = mysql_fetch_row(res);
for(j = 0;j < num_col;j++){
printf("%s %t",row[j]);
}
printf("\n");
}
mysql_free_result(res);
//6.关闭数据库
mysql_close(mysql);
return 0;
}