简体   繁体   English

需要帮助在C中打开sqlite3数据库

[英]Need help opening an sqlite3 database in C

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. 因此,我不是行业程序员,但是,我的任务是使用Modbus协议轮询指标,然后将信息记录到数据库中。 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. 但是,今天我能够使它正常工作,以尝试完善我的代码并使程序的主要部分(打开modbus连接,写入数据库,打开/创建数据库)成为在主过程中要调用的函数。周期,我在打开数据库时遇到了麻烦。 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. 当我调用该函数时,无论是在数据库的打开还是在代码的表部分的创建中,当我打印rc的值时,都会得到null。

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. 也许您错过了一个事实,即sqlite3_open()需要一个指向变量的指针,该变量指向一个sqlite3对象。 In your original code you declared a pointer to such an object and gave the address of that pointer to the open-function. 在原始代码中,您声明了一个指向此类对象的指针,并将该指针的地址提供给open函数。

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() ! 切记不要在调用sqlite3_open()db参数之前添加取消引用的&符号!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM