Listing 2. Basic C API Example
#include <string.h>
#include "sqlite.h"
int callback( void *p_data, int num_fields,
char **p_fields, char **p_col_names);
void main()
{
int ret;
int nrecs = 0;
char *errmsg;
/* Open the database. */
sqlite* p_db = sqlite_open("./db", 0777, 0);
if(p_db == 0)
{
printf("Could not open database.");
exit(1);
}
/* Select everything from the person table. */
ret = sqlite_exec( p_db,
"SELECT * from person limit 10;",
callback,
&nrecs,
errmsg);
if(ret!=SQLITE_OK)
{
printf("Error on SELECT: %s.\n", errmsg);
}
else
{
printf("Retrieved %i records.\n", nrecs);
}
/* Delete everything from the person table. */
sqlite_exec( p_db,
"DELETE * FROM person", 0,0,0);
/* On second thought, don't. */
sqlite_exec(p_db, "ROLLBACK", 0, 0, 0);
/* Close the database. */
sqlite_close(p_db);
}
int callback( void *p_data, int num_fields,
char **p_fields, char **p_col_names)
{
int i;
int *p_rn = (int*)p_data;
(*p_rn)++;
/* Print the field values. */
for(i=0; i < num_fields; i++)
{
printf("%s | " p_fields[i]);
}
return 0;
}
Copyright © 1994 - 2019 Linux Journal. All rights reserved.