#include<stdio.h>
#include<mysql.h>
//该程序向"my_tab"表中插入"qdr,M"项
int main(int argc,char * argv)
{
MYSQL conn;
int res;
mysql_init(&conn); //初始化连接
if(mysql_real_connect(&conn,"localhost","root","121684147","my_db",0,NULL,0)) //连接数据库"my_db"
{
printf("connected successfully!\n");
res=mysql_query(&conn,"insert into my_tab values('qdr','M')");
if(res)
{
printf("insert failed!\n");
mysql_close(&conn);
}
else
{
printf("insert succeed!\n");
mysql_close(&conn);
}
}
return 0;
}
#include<stdio.h>
#include<mysql.h>
//该程序从"my_db"数据库中查询表"my_tab"中的所有项,并且输出
int main(int argc,char * argv)
{
MYSQL conn;
MYSQL_RES * res_ptr; //指向查询结果的指针
MYSQL_FIELD * field; //字段结构指针
MYSQL_ROW result_row; //按行返回的查询信息
int res;
int row,column; //查询返回的行和列
int i,j;
mysql_init(&conn);
if(mysql_real_connect(&conn,"localhost","root","121684147","my_db",0,NULL,0))
{
printf("connected successfully!\n");
res=mysql_query(&conn,"select * from my_tab");
if(res)
{
printf("query failed!\n");
mysql_close(&conn);
}
else
{
printf("query succeed!\n");
res_ptr=mysql_store_result(&conn); //将查询结果给res_ptr
if(res_ptr)
{
column=mysql_num_fields(res_ptr); //取得查询结果的行,列
row=mysql_num_rows(res_ptr)+1;
printf("query to %d row!\n",row);
for(i=0;field=mysql_fetch_field(res_ptr);i++) //输出查询的字段名
printf("%s\t",field->name);
printf("\n");
for(i=1;i<row;i++) //按行输出查询结果
{
result_row=mysql_fetch_row(res_ptr);
for(j=0;j<column;j++)
printf("%s\t",result_row[j]);
printf("\n");
}
}
mysql_close(&conn);
}
}
return 0;
}