Skip to content

Instantly share code, notes, and snippets.

@nbulischeck
Created December 5, 2018 20:56
Show Gist options
  • Save nbulischeck/c228ab0135cee1d5b3aa2af7d4c20f79 to your computer and use it in GitHub Desktop.
Save nbulischeck/c228ab0135cee1d5b3aa2af7d4c20f79 to your computer and use it in GitHub Desktop.
Function that uses SQL parameter binding in C
#include <mysql.h>
int commit_db(MYSQL *con){
MYSQL_STMT *stmt;
MYSQL_BIND bind[2];
my_ulonglong affected_rows;
item_t *curr = items_list;
int count, param_count;
unsigned long str_length;
char str_data[64];
char *query = "INSERT INTO Items VALUES(?, ?)";
stmt = mysql_stmt_init(con);
if (!stmt){
printf("Failed to init SQL query!\n");
return -1;
}
if (mysql_stmt_prepare(stmt, query, strlen(query))){
printf("Failed to prepare SQL query!\n");
goto exit;
}
param_count = mysql_stmt_param_count(stmt);
if (param_count != 2){
printf("Invalid parameter count returned!\n");
goto exit;
}
memset(bind, 0, sizeof(bind));
bind[0].buffer_type = MYSQL_TYPE_STRING;
bind[0].buffer = (char *)str_data;
bind[0].buffer_length = 64;
bind[0].is_null = 0;
bind[0].length = &str_length;
bind[1].buffer_type = MYSQL_TYPE_LONG;
bind[1].buffer = (char *)&count;
bind[1].is_null = 0;
bind[1].length = 0;
if(mysql_stmt_bind_param(stmt, bind)){
printf("Bind param failed!\n");
goto exit;
}
while(curr != NULL){
count = (int)curr->quantity;
memset(str_data, 0, 64);
strncpy(str_data, curr->name, 64);
str_length = strlen(str_data);
if (mysql_stmt_execute(stmt)){
printf("Error executing query.\n");
goto exit;
}
affected_rows = mysql_stmt_affected_rows(stmt);
if (affected_rows != 1){
printf("Invalid affected rows by DB!\n");
goto exit;
}
curr = curr->next;
}
exit:
mysql_stmt_close(stmt);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment