vinod1 wrote:
> I am new to sqlite and C.
>
> I have not been able to write a code which would read row by row using
> sqlite3_step.
>
> Could anybody guide me please.
>
>   
Hi,

This code is equivalent to the very old callback style code shown at 
http://www.sqlite.org/quickstart.html.

It should provide the same results using the newer prepare/step/finalize 
set of calls that are discussed at http://www.sqlite.org/cintro.html.

Hopefully it provides a complete, if somewhat basic, intro to the use of 
the preferred C API functions.

#include <stdio.h>
#include <sqlite3.h>

int main(int argc, const char *argv[]){
  sqlite3 *db;
  sqlite3_stmt *stmt;
  int rc = 0;
  int col, cols;

  if( argc!=3 ){
    fprintf(stderr, "Usage: %s DATABASE SQL-STATEMENT\n", argv[0]);
  }else{
    // open the database file
    rc = sqlite3_open(argv[1], &db);
    if( rc ){
      fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
    }else{
      // prepare the SQL statement from the command line
      rc = sqlite3_prepare_v2(db, argv[2], -1, &stmt, 0);
      if( rc ){
        fprintf(stderr, "SQL error: %d : %s\n", rc, sqlite3_errmsg(db));
      }else{
        cols = sqlite3_column_count(stmt);
        // execute the statement
        do{
          rc = sqlite3_step(stmt);
          switch( rc ){
            case SQLITE_DONE:
              break;
            case SQLITE_ROW:
              // print results for this row
              for( col=0; col<cols; col++){
                const char *txt = (const char*)sqlite3_column_text(stmt, 
col);
                printf("%s = %s\n", sqlite3_column_name(stmt, col), txt 
? txt : "NULL");
              }
              break;
            default:
              fprintf(stderr, "Error: %d : %s\n",  rc, sqlite3_errmsg(db));
              break;
          }
        }while( rc==SQLITE_ROW );
        // finalize the statement to release resources
        sqlite3_finalize(stmt);
      }
      // close the database file
      sqlite3_close(db);
    }
  }
  return rc!=SQLITE_DONE;
}

HTH
Dennis Cote

_______________________________________________
sqlite-users mailing list
sqlite-users@sqlite.org
http://sqlite.org:8080/cgi-bin/mailman/listinfo/sqlite-users

Reply via email to