sqlite3 open, sqlite3 exec, slite3 close

Keywords: PHP SQL Database SQLite

sqlite3_open

  • SQLite3 open function prototype:
  • int sqlite3_open(
      const char *filename,   /* Database filename (UTF-8) */
      sqlite3 **ppDb          /* OUT: SQLite db handle */
    );
  • SQLite3 open is used to connect and open a database. If the database does not exist, a database file will be created and opened under the specified path.
  • void main(void) {
    ......

    sqlite3 *db; char *zErrMsg = 0; int rc; rc = sqlite3_open("testDB1.db", &db); if(rc){ fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); exit(0); } else { fprintf(stderr, "Opened database successfully\n"); }
    ......
    }

sqlite3_exec

  • Sqlite3'exec function prototype:
  • int sqlite3_exec(
      sqlite3,                                   /* An open database */
      const char *sql,                           /* SQL to be evaluated */
      int (*callback)(void*,int,char**,char**),  /* Callback function */
      void *,                                    /* 1st argument to callback */
      char **errmsg                              /* Error msg written here */
    );
  • SQLite3 exec is used to execute an sql statement with the following parameters:
  • Parameter 1: pointer obtained by opening the database;
  • Parameter 2: an sql statement, which is a string ending with "\ 0";
  • Parameter 3: the callback function provided by the user. If no callback function is required, NULL can be filled in. For example, if you do the insert operation and delete operation, there is no need to use the callback. When you do select, you need to use callback.
  • Parameter 4: the parameter to be passed by the callback function. If not, NULL can be filled.
  • Parameter 5: error message
  • Do not use callback example:
  • void main(void){
        ......
        sql = "INSERT INTO COMPANY VALUES (1, 'Paul', 32, 'California',     20000.00 ); "
        sqlite3_exec(db, sql, 0, 0, &zErrMsg);
    
    .....     
    }

     

  • Callback example:
  • static int callback(void *NotUsed, int argc, char **argv, char **azColName){
       int i;
       for(i=0; i<argc; i++){
          printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
       }
       printf("\n");
       return 0;
    }
    
    void main(void){
      ......
    
       /* Create SQL statement */
       sql = "SELECT * from COMPANY";
    
       /* Execute SQL statement */
       rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
       if( rc != SQLITE_OK ){
          fprintf(stderr, "SQL error: %s\n", zErrMsg);
          sqlite3_free(zErrMsg);
       }else{
          fprintf(stdout, "Operation done successfully\n");
       }    
    
    ......
    }

sqlite3_close

  • SQLite3 close function prototype:

  • int sqlite3_close(sqlite3*);  
  • SQLite3 close is used to close the database after the operation.

Posted by webmazter on Sat, 26 Oct 2019 10:57:27 -0700