So, I'm not a programmer by trade, however, I've been tasked with a program that will poll an indicator using the modbus protocol and then log the information into a database. I was able to get it working, however, today, in an attempt to refine my code and get the main parts of the program (open modbus connection, write to database, open/create database) to be functions to be called during the main cycle, I've encountered trouble with the opening of the database. When I call the function, I'm getting nulls when I print value of the rc, both in the opening of the database and the creation of the table portions of the code.
This is the way I had this before I tried to clean up the code and do it all by calling a function:
int main(int argc, char*argv[]){
sqlite3 *db;
//open database
int rc = sqlite3_open(db_name, &db);
if (rc != SQLITE_OK){
fprintf(stderr, "Cannot open database: %s\n",
sqlite3_errmsg(db));
sqlite3_close(db);
return 1;
}
char sql_query[1024];
// create sqlite table
snprintf(sql_query,sizeof(sql_query), "CREATE TABLE IF NOT EXISTS %s(%s INTEGER PRIMARY KEY,%s TEXT NOT NULL, %s TEXT NOT NULL, %s TEXT NOT NULL,%s REAL NOT NULL, %s REAL NOT NULL, %s REAL NOT NULL);",tbl_id1,tbl_col1,tbl_col2,tbl_col3,tbl_col4,tbl_col5,tbl_col6,tbl_col7);
rc = sqlite3_exec(db, sql_query, callback, 0, NULL);
if (rc != SQLITE_OK ){
fprintf(stderr, "Failed to select data\n");
fprintf(stderr, "SQL error: %s\n", NULL);
sqlite3_free(NULL);
sqlite3_close(db);
return 1;
}
I've no problem running it like that, and the function I'm trying to use is that same code enclosed in
void open_Database(db){//sqlite code}
Invoking the function:
open_Database(db) (same db declared in the main routine)
Maybe you missed the fact, that sqlite3_open()
needs a pointer to a variable pointing to a sqlite3
object. In your original code you declared a pointer to such an object and gave the address of that pointer to the open-function.
When you declare a sub-function doing that job, you should also give it a pointer-pointer:
void open_database (sqlite3 **db)
{
int rc;
rc = sqlite3_open(db_name, db);
// ... now do error checking
}
And remember to not add that de-referencing ampersand before the db
parameter in the call to sqlite3_open()
!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.