I'm beginning to learn how to use the MySQL C API and have encountered prepared statements. I haven't used these before in other languages so it's all new to me.
I've looked online and I've figured out how to use prepared statements to retrieve data from a SELECT
query, and now what I'm trying to do is to INSERT
some data and find out if it was successful. I've got the first part pretty much down, but my question is: how can I find out if my INSERT
was successfully executed?
I've had a read through some MySQL documents for the C API/prepared statements - and had a Google/search on SO. All I've been able to find examples of are SELECT
prepared statements and nothing more.
I've attached some code that I've created, which successfully inserts a row.
#include <mysql/mysql.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "session.h"
char *createSessionId(MYSQL *dbc) {
const char *sPS2 = "INSERT INTO `sessions` (`SessionID`) VALUES (?)";
char *sID;
MYSQL_STMT *stmt;
MYSQL_BIND param[1];
unsigned long l = 32;
// Allocate a statement handle
stmt = mysql_stmt_init(dbc);
if(stmt == NULL) {
printf("Unable to create new session: Could not init statement handle\n");
return NULL;
}
// Init
memset(param, 0, sizeof(param));
sID = malloc(33);
sprintf(sID, "01234567890123456789012345678901");
if(mysql_stmt_prepare(stmt, sPS2, strlen(sPS2)) != 0) {
printf("Unable to create new session: Could not prepare statement\n");
return NULL;
}
// Initialise param structure
param[0].buffer_type = MYSQL_TYPE_VARCHAR;
param[0].buffer = sID;
param[0].is_unsigned = 0;
param[0].is_null = 0;
param[0].length = &l;
// Bind param structure to statement
if(mysql_stmt_bind_param(stmt, param) != 0) {
printf("Unable to create new session: Could not bind parameters\n");
return NULL;
}
// Execute prepared statement
if(mysql_stmt_execute(stmt) != 0) {
printf("Unable to create new session: Could not execute statement\n");
return NULL;
}
mysql_stmt_free_result(stmt);
mysql_stmt_close(stmt);
return sID;
}