-1

I'm using sqlite3 in c and I created a function called open_database with no return type:

void open_database(const char* database_name, sqlite3* db)

and all it does is open the database:

Doesnt work: 

void open_database(const char* database_name, sqlite3* db) {

    int return_code;

    return_code = sqlite3_open(database_name, &db);

    if(return_code) {
        printf("Issue opening database\n");
        exit(1);
    } else {
        printf("Datbase Opened.\n");
    }
}


Works:

sqlite3* open_database(const char* database_name, sqlite3* db) {
    int return_code;

    return_code = sqlite3_open(database_name, &db);

    if(return_code) {
        printf("Issue opening database\n");
        exit(1);
    } else {
        printf("Datbase Opened.\n");
        return db;
    }
}

The problem is when I then call the function and try to use it elsewhere it fails with a NULL error type? (sqlite error: (null)). But if I change it from void to sqlite3 and return the db object it works?

sqlite3* db;


Works: 

db = open_database("test_db", db);
create_table(db);
insert_into_table(db);
close_database(db);


Doesnt work: 

open_database("test_db", db);
create_table(db);
insert_into_table(db);
close_database(db);

I tried searching around the documentation and other areas but have found no reasoning why. Any insight into why this happens would be awesome. Thanks.

Extra:

heres one of the functions that then uses the database:

void create_table(sqlite3* db) {

    char* sql;
    char *zErrMsg = NULL;
    int return_code;

    /* Create SQL statement */
    sql = "CREATE TABLE COMPANY("  \
      "ID INT PRIMARY KEY     NOT NULL," \
      "NAME           TEXT    NOT NULL," \
      "AGE            INT     NOT NULL," \
      "ADDRESS        CHAR(50)," \
      "SALARY         REAL );";

    //printf("First Statement: %s\n", sql);

   /* Execute SQL statement */
   return_code = sqlite3_exec(db, sql, NULL, NULL, &zErrMsg);

   if( return_code != SQLITE_OK ){

      fprintf(stderr, "SQL error: %s\n", zErrMsg);
      //printf("Error creating table.\n");
      sqlite3_free(zErrMsg);

   } else {
      fprintf(stdout, "Table created successfully\n");
   }

}
iG Cloud
  • 47
  • 1
  • 7

1 Answers1

1

similar to this question, when passing in the pointer and then attempting to modifying it by calling sqlite3_open(), you are modifying a copy of that pointer which is local to the function. if you return it, you'll get back your changes.

if you want it to return void, try to define it like this...

void open_database(const char* database_name, sqlite3** db) {

    int return_code;

    return_code = sqlite3_open(database_name, db);

    if(return_code) {
        printf("Issue opening database\n");
        exit(1);
    } else {
        printf("Datbase Opened.\n");
    }
}

and call it like this

sqlite3* db;
open_database("test_db", &db);
bitbangs
  • 506
  • 3
  • 6