I needed a quick excercise this morning.  Never used table_info() before.
table_info() will be faster than doing "select *" I would think in most all 
cases.



#include <iostream>
#include <sstream>
#include <sstream>
#include "sqlite3.h"

using namespace std;

bool dbExists(string dbName) {
  sqlite3 *db;
  int rc = sqlite3_open_v2(dbName.c_str(), &db, SQLITE_OPEN_READONLY, NULL);
  if(rc != SQLITE_OK) {
    return false;
  }
  rc = sqlite3_close(db);
  if(rc != SQLITE_OK) {
    cerr << "Error on sqlite3_close??" << endl;
  }
  return true;
}

bool tableExists(string dbName, string table) {
  sqlite3 *db;
  int rc = sqlite3_open_v2(dbName.c_str(), &db, SQLITE_OPEN_READONLY, NULL);
  if(rc != SQLITE_OK) {
    return false; // db doesn't exist
  }

  sqlite3_stmt *stmt;
  stringstream ss;
  ss << "pragma table_info(" << table << ");";
  rc = sqlite3_prepare_v2( db, ss.str().c_str() , -1, &stmt, NULL );
  if(rc != SQLITE_OK) {
    cerr << "Error on sqlite3_prepare_v2: " << sqlite3_errmsg(db) << endl;
  }
  rc = sqlite3_step(stmt);
  if(rc != SQLITE_DONE && rc != SQLITE_ROW) {
    cerr << "Error on sqlite3_step: " << sqlite3_errmsg(db) << endl;
  }

  bool myReturn = false;
  if (sqlite3_data_count(stmt) > 0) {
    myReturn = true;
  }
  sqlite3_finalize(stmt);
  sqlite3_close(db);
  return myReturn;
}


Michael D. Black
Senior Scientist
Advanced Analytics Directorate
Advanced GEOINT Solutions Operating Unit
Northrop Grumman Information Systems




From: sqlite-users-boun...@sqlite.org [sqlite-users-boun...@sqlite.org] on 
behalf of Arbol One [arbol...@gmail.com]
Sent: Friday, July 20, 2012 5:51 AM
To: SqLite
Subject: EXT :[sqlite] database AND table already exist?


Is there a way to find out if a certain database AND table already exist?

In my C++ program I would like to query SQLite3 to find out if a database
already exists and also if a particular table exists in that database. Is
there a way to do this?

I am using std i/o methods to check for the existing SQLite3 file containing
the database, but I don't have a way to find out if the table in question
does in fact exist.



TIA



Freedom of speech does not translate to freedom of insulting



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

Reply via email to