1. 添加头文件
# apt-get install libmysqlclient-dev
引入头文件
#include <mysql/mysql.h>
2. 举例
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)
int mysql_real_query(MYSQL *mysql, const char *query, unsigned int length)
int main()
{
MYSQL mysql;
MYSQL_RES *res;
MYSQL_ROW row;
char sql[50] = {0};
int t;
sprintf(sql, "select * from user");
mysql_init(&mysql); //初始化mysql结构
//if(mysql_real_connect(&mysql, NULL, "root", "123456", "mysql", 3306, NULL, 0))
if(mysql_real_connect(&mysql, "127.0.0.1", "root", "123456", "mysql", 0, NULL, 0))
{
printf("连接数据库成功!
");
}
else
{
printf("连接数据库失败:%s
", mysql_error(&mysql));
}
t = mysql_real_query(&mysql, sql, (unsigned int)strlen(sql)); //在服务器上执行定义的sql语句
if(t)
{
printf("查询语句错误:%s
", mysql_error(&mysql));
}
else
{
res = mysql_store_result(&mysql); //读取结果置于结构中
while(row = mysql_fetch_row(res)) //检索结果集的下一行
{
unsigned long *lengths;
lengths = mysql_fetch_lengths(res); //当前行列的长度
for(t = 0; t < mysql_num_fields(res); t++) //获取结合集中的行数(行内)
{
printf("%d ", (int)lengths[t]);
printf("%s
", row[t] ? row[t] : "NULL"); //防止指针为空报段错误
}
printf("
");
}
mysql_free_result(res);
}
printf("释放结果集的空间...
");
mysql_close(&mysql); //释放数据库
return 0;
}
需要链接库:libmysqlclient.so
3. 结果集中的行数
mysql_field_count(MYSQL *mysql)