Batch Operations with MariaDB Connector/C
MariaDB Connector/C supports batch (bulk) operations by binding an array of parameter sets to a single prepared statement, sending many rows to the server in one execution.
Array Binding
Code Example: Column-wise Binding
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mysql.h>
int main(int argc, char *argv[])
{
// Initialize Connection
MYSQL *conn;
if (!(conn = mysql_init(0)))
{
fprintf(stderr, "unable to initialize connection struct\n");
exit(1);
}
// Connect to the database
if (!mysql_real_connect(
conn, "mariadb.example.net", "db_user", "db_user_password",
"test", 3306, NULL, 0))
{
fprintf(stderr, "Error connecting to Server: %s\n", mysql_error(conn));
mysql_close(conn);
exit(1);
}
// One array per parameter. For the string columns the buffer is an array
// of pointers, and each column has its own array of indicators.
const char *first_names[] = { "John", "Jon", "Johnny" };
const char *last_names[] = { "Smith", "Smith", "Smith" };
const char *emails[] = { "john.smith@example.com", "jon.smith@example.com", "johnny.smith@example.com" };
char first_ind[] = { STMT_INDICATOR_NTS, STMT_INDICATOR_NTS, STMT_INDICATOR_NTS };
char last_ind[] = { STMT_INDICATOR_NTS, STMT_INDICATOR_NTS, STMT_INDICATOR_NTS };
char email_ind[] = { STMT_INDICATOR_NTS, STMT_INDICATOR_NTS, STMT_INDICATOR_NTS };
unsigned int array_size = 3;
// Initialize and prepare the statement
MYSQL_STMT *stmt = mysql_stmt_init(conn);
if (mysql_stmt_prepare(stmt,
"INSERT INTO test.contacts(first_name, last_name, email) VALUES (?, ?, ?)", -1))
{
fprintf(stderr, "Error preparing statement: %s\n", mysql_stmt_error(stmt));
exit(1);
}
// Bind each parameter to its array
MYSQL_BIND bind[3];
memset(bind, 0, sizeof(bind));
bind[0].buffer_type = MYSQL_TYPE_STRING;
bind[0].buffer = first_names;
bind[0].u.indicator = first_ind;
bind[1].buffer_type = MYSQL_TYPE_STRING;
bind[1].buffer = last_names;
bind[1].u.indicator = last_ind;
bind[2].buffer_type = MYSQL_TYPE_STRING;
bind[2].buffer = emails;
bind[2].u.indicator = email_ind;
// Set only the batch size; without STMT_ATTR_ROW_SIZE the binding is column-wise
mysql_stmt_attr_set(stmt, STMT_ATTR_ARRAY_SIZE, &array_size);
// Bind and execute the batch in a single call
if (mysql_stmt_bind_param(stmt, bind) || mysql_stmt_execute(stmt))
{
fprintf(stderr, "Error executing batch: %s\n", mysql_stmt_error(stmt));
exit(1);
}
// Close the statement and the connection
mysql_stmt_close(stmt);
mysql_close(conn);
return 0;
}Code Example: Row-wise Binding
See Also
Last updated
Was this helpful?

