DML with MariaDB Connector/C
MariaDB Connector/C supports DML operations including INSERT, UPDATE, DELETE, and SELECT, using prepared statements and result sets to manipulate data in MariaDB databases.
DML Operations
Code Example: INSERT, UPDATE, DELETE
#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);
}
// Values to insert
char first_name[] = "John";
char last_name[] = "Smith";
char email[] = "john.smith@example.com";
// 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 the values to the statement parameters
MYSQL_BIND bind[3];
memset(bind, 0, sizeof(bind));
bind[0].buffer_type = MYSQL_TYPE_STRING;
bind[0].buffer = first_name;
bind[0].buffer_length = strlen(first_name);
bind[1].buffer_type = MYSQL_TYPE_STRING;
bind[1].buffer = last_name;
bind[1].buffer_length = strlen(last_name);
bind[2].buffer_type = MYSQL_TYPE_STRING;
bind[2].buffer = email;
bind[2].buffer_length = strlen(email);
// Execute the statement
if (mysql_stmt_bind_param(stmt, bind) || mysql_stmt_execute(stmt))
{
fprintf(stderr, "Error adding contact: %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: SELECT
Last updated
Was this helpful?

