//simple_mysql_insert2.c
#include <stdlib.h>
#include <stdio.h>
#include <mysql.h>
int main(int argc, char *argv[]){
MYSQL my_connection;
MYSQL_RES * res_ptr;
MYSQL_ROW sqlrow;
int ret = -1;
const char* host = "localhost";
const char* user = "root";
const char* password = "!QAZ2wsx";
const char* dbname = "rick";
mysql_init(&my_connection);
MYSQL* conn_ptr= mysql_real_connect(&my_connection ,host, user, password,dbname,0,NULL,0);
if(conn_ptr){
printf("Connection succeed!\n");
const char* sql = "insert into children(fname, age) values('John', 8)";
ret = mysql_query(&my_connection, sql);
if(!ret){
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));
}
//get LAST_INSERT_ID
ret = mysql_query(&my_connection, "select LAST_INSERT_ID()");
if(ret!= 0){
fprintf(stderr, "select error %d : %s \n", mysql_errno(&my_connection), mysql_error(&my_connection));
}else{
res_ptr = mysql_use_result(&my_connection);
if(res_ptr){
while((sqlrow=mysql_fetch_row(res_ptr))){
printf("We insert childno %s\n", sqlrow[0]);
}
mysql_free_result(res_ptr);
}
}
mysql_close(&my_connection);
}else{
fprintf(stderr, "Connection failed!\n");
if(mysql_errno(&my_connection)){
fprintf(stderr, "Connection error %d: %s\n", mysql_errno(&my_connection), mysql_error(&my_connection));
}
}
return 0;
}
运行:
xx@ubuntu:~/workspace/mysql-test$ g++ -o test-insert2 simple_mysql_insert2.c -I/usr/include/mysql -L/usr/lib/mysql -lmysqlclient
xx@ubuntu:~/workspace/mysql-test$ ./test-insert2
Connection succeed!
Inserted 1 rows
We insert childno 7