将SQLite添加到Android NDK项目

时间:2017-01-14 13:03:47

标签: android c++ sqlite android-ndk

我是android开发人员,但在android ndk中是新的,现在我正在尝试使用c ++通过android ndk编写应用程序,所有使用数据库的工作也应该用c ++代码完成。我在项目中添加了sqlite(我不确定我是否正确执行):我下载并将这四个文件(shell.c,sqlite3.c,sqlite3.h,slite3ext.h)保存到src / main / cpp / sqlite文件夹。这是我的CMakeList.txt,我将sqlite添加到项目中:

add_library(native-lib

             SHARED

             src/main/cpp/native-lib.cpp
             src/main/cpp/sqlite/sqlite3.c
             )

我做对了吗?我如何在代码中使用它(连接到数据库,创建表,插入数据,更新数据......)?

1 个答案:

答案 0 :(得分:1)

您需要在项目中包含以下3个文件:sqlite3.csqlite3.hsqlite3ext.h(不确定最后一个文件)。基本操作(创建db,创建表和插入值):

bool createTable() {

    /* Open database */
    sqlite3 *db;
    char *zErrMsg = 0;
    int rc;
    rc = sqlite3_open(databaseName, &db);
    if (rc != SQLITE_OK) {
        //Can't open database/
        sqlite3_open_v2(DB_FILE, &db, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, NULL);
    }

    /* Create SQL statement */
    const char *createQuery =
            "CREATE TABLE IF NOT EXISTS cities (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT);";

    /* Execute SQL statement */
    rc = sqlite3_exec(db, createQuery, callback, 0, &zErrMsg);

    if (rc != SQLITE_OK) {
        sqlite3_free(zErrMsg);
        return false;
    }
    sqlite3_close(db);
    return true;
}

插入:

bool insertToDb(CityWeather *pCityWeather) {
    sqlite3 *db;
    char *zErrMsg = 0;
    int rc;

    /* Open database */
    rc = sqlite3_open(databaseName, &db);
    if (rc) {
        sqlite3_open_v2(DB_FILE, &db, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, NULL);
    }

    const char *pCityName = pCityWeather->getName().c_str();
    char insertQuery[50];
    strcpy (insertQuery,"INSERT INTO cities (name) VALUES ('");
    strcat (insertQuery, pCityName);
    strcat (insertQuery, "');");
    puts (insertQuery);

    delete pCityWeather;

    /* Execute SQL statement */
    rc = sqlite3_exec(db, insertQuery, callback, 0, &zErrMsg);
    if (rc != SQLITE_OK) {
        sqlite3_free(zErrMsg);
    }
    sqlite3_close(db);
    return true;
}