- The
sqlite3_exec function takes a SQL string and executes each statement in the SQL string
- It can also take a row data callback that gets called with each rows data if there is any (this field is nullable)
- If there is an error the errmsg pointer will have a message
- In this case it will need to be free'd using
sqlite3_free
- The following example shows creating a database and executing multiple statements to insert data
#include <stdio.h>
#include "sqlite_3.43.1/sqlite3.h"
int main(int argc, char **argv)
{
sqlite3 *db = NULL;
int result;
char *err_msg = NULL;
printf("Hello, SQLite3\n");
result = sqlite3_open("test.db", &db);
if (result != SQLITE_OK) {
fprintf(stderr, "Unable to open db: %s\n",
sqlite3_errmsg(db));
return 1;
}
char *sql =
"DROP TABLE IF EXISTS test;"
"CREATE TABLE test(id INTEGER PRIMARY KEY, msg TEXT);"
"INSERT INTO test(msg) VALUES(\"abc\");"
"INSERT INTO test(msg) VALUES(\"123\");";
result = sqlite3_exec(db, sql, NULL, NULL, &err_msg);
if (result != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", err_msg);
sqlite3_free(err_msg);
sqlite3_close(db);
return 1;
}
sqlite3_close(db);
return 0;
}
- The following example shows defining a row callback when querying the db
#include <stdio.h>
#include "sqlite_3.43.1/sqlite3.h"
int row_callback(void *user_data, int row_count, char **values,
char **columns);
int main(int argc, char **argv)
{
sqlite3 *db = NULL;
int result;
char *err_msg = NULL;
printf("Hello, SQLite3\n");
result = sqlite3_open("test.db", &db);
if (result != SQLITE_OK) {
fprintf(stderr, "Unable to open db: %s\n",
sqlite3_errmsg(db));
return 1;
}
char *sql =
"DROP TABLE IF EXISTS test;"
"CREATE TABLE test(id INTEGER PRIMARY KEY, msg TEXT);"
"INSERT INTO test(msg) VALUES(\"abc\");"
"INSERT INTO test(msg) VALUES(\"123\");";
result = sqlite3_exec(db, sql, NULL, NULL, &err_msg);
if (result != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", err_msg);
sqlite3_free(err_msg);
sqlite3_close(db);
return 1;
}
sql = "SELECT * FROM test;";
result = sqlite3_exec(db, sql, row_callback, NULL, &err_msg);
if (result != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", err_msg);
sqlite3_free(err_msg);
sqlite3_close(db);
return 1;
}
sqlite3_close(db);
return 0;
}
int row_callback(void *user_data, int row_count, char **values,
char **columns)
{
printf("test row\n");
for (int i = 0; i < row_count; i++) {
printf("\t%s: %s\n", values[i], columns[i]);
}
return 0;
}
- This returns the following output
./hello_sqlite
Hello, SQLite3
test row
1: id
abc: msg
test row
2: id
123: msg