建立mysql C开发环境
参考: feizf.blogbus.com/logs/30689586.html
命令:
#安装开发包
sudo apt-get install libmysqlclient15-dev
相关mysql头文件和库文件安装在/usr/include/mysql/和/usr/lib/mysql目录
编译操作数据库的C源文件命令是:
gcc demo.c -I /usr/include/mysql -L /usr/lib/mysql -lmysqlclient -o demo
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
测试开发环境是否搭建好的代码:
#include<stdlib.h>
#include<mysql.h>
/*
* compile command:
* gcc test.c -I /usr/include/mysql -L /usr/lib/mysql -lmysqlclient -o test
*/
int main()
{
MYSQL mysql;
mysql_init(&mysql);
return 0;
}
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
简单示例:
menagerie.pet表:
#include<mysql.h>
#include<stdlib.h>
int main(int argc, char **argv)
{
MYSQL mysql_conn;
MYSQL_ROW rows;
MYSQL_RES *mysql_result;
if(mysql_init(&mysql_conn))
{
if(mysql_real_connect(&mysql_conn, "localhost", "zhaoli", "*******", "menagerie", 0, NULL, 0))
{
if(mysql_query(&mysql_conn, "select * from pet"))
{
fprintf(stderr, "Failed to query, Error: %s\n", mysql_error(&mysql_conn));
}
else
{
mysql_result = mysql_store_result(&mysql_conn);
if(mysql_result)
{
int num_fields = mysql_num_fields(mysql_result);
int num_rows = mysql_num_rows(mysql_result);
printf("Rows: %d, Fields: %d\n", num_rows, num_fields);
while(rows = mysql_fetch_row(mysql_result))
{
int i;
unsigned long *lengths;
lengths = mysql_fetch_lengths(mysql_result);
for(i=0; i<num_fields; i++)
{
printf("%.*s\t", (int)lengths[i]==0 ? 4 : (int)lengths[i], rows[i] ? rows[i] : "NULL");
}
printf("\n");
}
}
else
{
if(mysql_errno(&mysql_conn))
fprintf(stderr, "Failed to mysql_store_result, Error: %s\n", mysql_error(&mysql_conn));
}
}
}
else
{
fprintf(stderr, "Failed to connect to database, Error: %s\n", mysql_error(&mysql_conn));
}
}
else
{
fprintf(stderr, "Failed to initialize the MYSQL, Error: %s\n", mysql_error(&mysql_conn));
}
}