MySQL C庫的使用
1.初始化和清理
MYSQL mysql; //數(shù)據(jù)庫句柄
MYSQL_RES* res; //查詢結(jié)果集
MYSQL_ROW row; //記錄結(jié)構(gòu)體(就是一行數(shù)據(jù))
mysql_init(&mysql); //初始化數(shù)據(jù)庫(單線程模式mysql_init自動調(diào)用匣吊,線程不安全)
mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, "gbk"); //設(shè)置字符編碼
int ret = mysql_options(&mysql, MYSQL_OPT_CONNECT_TIMEOUT, &to); //超時設(shè)置暑椰,失敗返回非0
int reconn = 1;
ret = mysql_options(&mysql, MYSQL_OPT_RECONNECT, &reconn); //設(shè)置自動重連
mysql_free_result(res); //關(guān)閉結(jié)果集
mysql_close(&mysql); //關(guān)閉數(shù)據(jù)庫連接
mysql_library_end();
2.連接與查詢數(shù)據(jù)庫
mysql_real_connect(&mysql,"127.0.0.1","root","root123456","hui",3306,NULL,0) //失敗返回NULL
const char* sql = "select * from students"; //sql語句
ret = mysql_real_query(&mysql, sql,strlen(sql)); //查詢
res = mysql_store_result(&mysql); //獲取查詢結(jié)果集
int field_num = mysql_num_fields(res); //獲取表字段的數(shù)量
MYSQL_FIELD* fields = mysql_fetch_fields(res); //獲取表字段名數(shù)組
MYSQL_ROW row = mysql_fetch_row(res)侄刽; //從結(jié)果集中獲取一行數(shù)據(jù)
unsigned long* len_ptr = mysql_fetch_lengths(res);//從結(jié)果集中獲取一行字段數(shù)據(jù)的長度數(shù)組
sample
#include <mysql.h>
#include <iostream>
#include <stdio.h>
int main()
{
MYSQL mysql; //數(shù)據(jù)庫句柄
MYSQL_RES* res; //查詢結(jié)果集
MYSQL_ROW row; //記錄結(jié)構(gòu)體(就是一行數(shù)據(jù))
mysql_init(&mysql); //初始化數(shù)據(jù)庫(單線程模式mysql_init自動調(diào)用泉孩,線程不安全)
/// <summary>
/// mysql_options設(shè)置請在連接前設(shè)置
/// </summary>
mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, "gbk"); //設(shè)置字符編碼
int to = 3;
int ret = mysql_options(&mysql, MYSQL_OPT_CONNECT_TIMEOUT, &to); //超時設(shè)置,失敗返回非0
if (ret != int(0))
{
std::cout << "設(shè)置超時失敗" << std::endl;
}
int reconn = 1;
ret = mysql_options(&mysql, MYSQL_OPT_RECONNECT, &reconn); //設(shè)置自動重連
if (ret != 0)
{
std::cout << "自動重連設(shè)置失敗" << std::endl;
}
/// <summary>
///連接數(shù)據(jù)庫
/// </summary>
if (mysql_real_connect(&mysql,"127.0.0.1","root","root123456","hui",3306,NULL,0)==NULL)
{
printf("錯誤原因:%s\n", mysql_error(&mysql));
printf("連接失敗");
exit(-1);
}
/// <summary>
/// 查詢數(shù)據(jù)萧芙;獲取結(jié)果集
/// </summary>
const char* sql = "select * from students";
ret = mysql_real_query(&mysql, sql,strlen(sql));
if (ret!= 0)
{
printf("ret:%s\n", mysql_error(&mysql));
}
res = mysql_store_result(&mysql);
//獲取表字段的數(shù)量
int field_num = mysql_num_fields(res);
std::cout << "數(shù)據(jù)庫表字段有" << field_num << "個" << std::endl;
MYSQL_FIELD* fields = mysql_fetch_fields(res); //獲取表字段名數(shù)組
for (int i = 0; i < field_num; i++)
{
printf("Field %u is %s\n", i, fields[i].name);
}
while (row = mysql_fetch_row(res))
{
unsigned long* len_ptr = mysql_fetch_lengths(res); //獲取結(jié)果集的長度要在mysql_fetch_row后
for (int i = 0;i<field_num;++i)
{
printf("字段%d的長度為:%d,字段名為:%s,數(shù)據(jù)為:%s\n",i, len_ptr[i], fields[i].name ,row[i]);
}
}
/// <summary>
///釋放結(jié)果集给梅;關(guān)閉數(shù)據(jù)庫
/// </summary>
mysql_free_result(res);
mysql_close(&mysql);
mysql_library_end();
system("pause");
return 0;
}