#include <stdlib.h>
#include<stdio.h>
#include <mysql.h>
int main()
{
MYSQL my_connection;
MYSQL_RES *res_ptr;
MYSQL_ROW sqlrow;
int res;
mysql_init(&my_connection); if(mysql_real_connect(&my_connection,"localhost","rick","bar","rick",0,NULL,0))
{
printf("connection success\n");
res=mysql_query(&my_connection,"insert into children (fname ,age ) values(‘robert’,7)");
if(!res)
{
printf("inserted %lu rows\n",(unsigned long)mysql_affected_rows(&my_connection));
}
else
{
fprintf(stderr,"insert error %d:%s\n",mysql_errno(&my_connection),mysql_error(&my_connection));
}
res=mysql_query(&my_connetion,"select LAST_INSERT_ID()");
if(res)
{
printf("select error:%s\n",mysql_error(&my_connection));
}
else
{
res_ptr = mysql_use_result(&my_connection); //获取最后一次操作的行号
if(res_ptr)
{
while((sqlrow=mysql_fetch_row(res_ptr)))
{
printf("we inserted childno %s\n",sqlrow[0]);
}
mysql_free_result(res_ptr);
}
mysql_close(&my_connection);
}
}
运行之后的结果:
connection sucess
inserted 1 rows
we insertde childno 6
若想返回sqlrow[0]
int mysql_result()
{
int *id=0; //定义一个地址
MYSQL_RES* res=mysql_use_result(pDB->getMySQL());
if(res)
{
while((Row=mysql_fetch_row(res)))
{
printf("we inserted row is %s\n",Row[0]);
*id=atoi(Row[0]);
printf("mysql id ==%d\n",*id);
}
}
mysql_free_result(res);
return *id; //返回地址即可
}
这是我在linux程序设计p292,查找到的