Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting the sqlite3 table into file using "C" execute API

Tags:

c

sqlite

I am using sqlite3 version 3.6.23.1 in fedora 14.I am able to export table into the file using command prompt like this,

sqlite3 data.db

sqlite> .output sample.txt;

sqlite> select *from sample;

I want handle this case at the application level.

I am using sqlite3 open source "C" API to execute this command in application level.

execute("delete from sample:);// working fine

execute(".output sample.txt"); //Not working

its throwing error called "SQL error in sqlite3_exec: near ".": syntax error"

Please suggest me how do i create a file to import the data using this API.

Function definition of the API.

int execute(const char* fmt, ...)
{

    char *err_messg;

    int ret = 0, result = 0;

    char sql_string[1024] = ""; //this honestly needs to be more elegant; will do for now

    va_list args;

    va_start(args, fmt);

    ret = vsprintf(sql_string, fmt, args);

    va_end(args);

    printf("sql_string: %s\n", sql_string);

    if (!ret)
        result = 0;
    else
        result = 1;

    if (result != -1)
    {

        if (sqlite3_exec(db_conn, sql_string, NULL, 0, &err_messg) == SQLITE_OK)    //Actual API which will work with database.
        {
            return SUCCESS;
        }
        else
        {
            printf("\n SQL error in sqlite3_exec: %s\n", err_messg);
            return DBEXCE_FAIL;
        }
    }
    return SUCCESS;
}
like image 414
user1495372 Avatar asked Jul 02 '12 07:07

user1495372


3 Answers

The SQLite API call you are using only accepts SQL:
"The sqlite3_exec() interface runs zero or more UTF-8 encoded, semicolon-separate SQL statements passed into its 2nd argument, in the context of the database connection passed in as its 1st argument." [from http://www.sqlite.org/c3ref/exec.html]

If you browse through the source of SQLite you can see that the .output command opens a file and then uses the sqlite3_snprintf API to write the contents of the query result to the opened file handle.

The most recent source that shows what is happening is here:
http://www.sqlite.org/src/artifact/076e1c90d594644f36027c8ecff9a392cf2d3a06

The relevant part for .output is this:

if( c=='o' && strncmp(azArg[0], "output", n)==0 && nArg==2 ){
    if( p->outfile[0]=='|' ){
      pclose(p->out);
    }else{
      output_file_close(p->out);
    }
    p->outfile[0] = 0;
    if( azArg[1][0]=='|' ){
      p->out = popen(&azArg[1][1], "w");
      if( p->out==0 ){
        fprintf(stderr,"Error: cannot open pipe \"%s\"\n", &azArg[1][1]);
        p->out = stdout;
        rc = 1;
      }else{
        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", azArg[1]);
      }
    }else{
      p->out = output_file_open(azArg[1]);
      if( p->out==0 ){
        if( strcmp(azArg[1],"off")!=0 ){
          fprintf(stderr,"Error: cannot write to \"%s\"\n", azArg[1]);
        }
        p->out = stdout;
        rc = 1;
      } else {
        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", azArg[1]);
      }
    }
like image 123
rmcnew Avatar answered Sep 20 '22 09:09

rmcnew


The .output command of the SQLite shell is a feature of that shell (along with all the other commands that begin with .). If you're working with the C interface, you should do a query to fetch the rows you want, and iterate over them writing them one at a time to the file.

Adapting from the sample code found in this tutorial…

static int callback(void *handle, int argc, char **argv, char **azColName) {
     FILE *f = handle;
     int i;
     const char *sep = "";
     for (i=0;i<argc;i++) {
         fprintf(f, "%s\"%s\"", sep, argv[i]);
         sep = ", ";
     }
     fprintf(f, "\n");
     return 0;
}
const char *sql = "SELECT * FROM sample;";
sqlite3 *db;
FILE *f = fopen("sample.csv", "w"); // ought to check for errors here; demo code!
char *errs = NULL;

if (sqlite3_open("data.db", &db)) {
    fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
    sqlite3_close(db);
    exit(1);
}
if (sqlite3_exec(db, sql, callback, f, &errs) != SQLITE_OK)
    fprintf(stderr, "SQL error: %s\n", errs);
sqlite3_close(db);
like image 42
Donal Fellows Avatar answered Sep 24 '22 09:09

Donal Fellows


The post seems a bit old, but I just want to update for any visitor looking for similar information. There is an open source C/C++ API for SQLite3 database import/export functions.

The API can be accessed via here

like image 25
fnisi Avatar answered Sep 21 '22 09:09

fnisi