Skip to content

Instantly share code, notes, and snippets.

@ewalk153
Last active November 2, 2022 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ewalk153/555c21db5afceb9b3a0604ba7bd1a06e to your computer and use it in GitHub Desktop.
Save ewalk153/555c21db5afceb9b3a0604ba7bd1a06e to your computer and use it in GitHub Desktop.
Example of how to run sqlite3_deserialize
#include <sqlite3.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_FILE_SIZE 1000000
// build with
// cc run_sqlite3_deserialize.c -lsqlite3 -o sqlite3_deserialize
// create db with:
// echo "create table pizza(name, color); insert into pizza(name, color) values ('margarita', 'red');" | sqlite3 pizza.db
int callback(void *, int, char **, char **);
int load(sqlite3 *db, char *name, unsigned char *dbuf, unsigned long *fileLen);
int main(void) {
sqlite3 *db;
char *err_msg = 0;
unsigned char *dbuf = malloc(sizeof(unsigned char)*MAX_FILE_SIZE);
unsigned long fileLen;
int rc = sqlite3_open(":memory:", &db);
if (rc != SQLITE_OK) {
fprintf(stderr, "Cannot open database: %s\n",
sqlite3_errmsg(db));
sqlite3_close(db);
return 1;
}
load(db, "pizza.db", dbuf, &fileLen);
free(dbuf);
char *sql = "SELECT * FROM pizza";
rc = sqlite3_exec(db, sql, callback, 0, &err_msg);
if (rc != SQLITE_OK ) {
fprintf(stderr, "Failed to select data\n");
fprintf(stderr, "SQL error: %s\n", err_msg);
sqlite3_free(err_msg);
sqlite3_close(db);
return 1;
}
sqlite3_close(db);
return 0;
}
int load(sqlite3 *db, char *name, unsigned char *dbuf, unsigned long *fileLen)
{
FILE *file;
//Open file
file = fopen(name, "rb");
if (!file)
{
fprintf(stderr, "Unable to open file %s", name);
return 1;
}
//Get file length
fseek(file, 0, SEEK_END);
*fileLen=ftell(file);
fseek(file, 0, SEEK_SET);
//Read file contents into buffer
fread(dbuf, *fileLen, 1, file);
fclose(file);
printf("File size: %ld\n", *fileLen);
sqlite3_deserialize(db, NULL, dbuf, *fileLen, *fileLen, 0);
return 0;
}
int callback(void *NotUsed, int argc, char **argv,
char **azColName) {
NotUsed = 0;
for (int i = 0; i < argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment