SQLite使用
Posted Sawyer Ford
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQLite使用相关的知识,希望对你有一定的参考价值。
sqlite3_exec虽然好用,但是一般不推荐直接使用。
常用的一组操作是:
关于sqlite3_exec和sqlite3_prepare_v2的使用场景,建议如下:
一个小DEMO:
#include <stdio.h> #include <sqlite3.h> int main(int argc, char **argv) { sqlite3 *db; int rc; rc = sqlite3_open("test.db", &db); if (rc) { printf("Can\'t open database: %s\\n", sqlite3_errmsg(db)); sqlite3_close(db); return 1; } else { printf("Open database successfully\\n"); } sqlite3_stmt *stmt = NULL; const char *sql = "SELECT * FROM COMPANY"; // const char *sql = "SELECT * FROM COMPANY WHERE AGE=?;"; sqlite3_prepare_v2(db, sql, -1, &stmt, NULL); // sqlite3_bind_int(stmt, 1, 25); int col_count = sqlite3_column_count(stmt); printf("该条记录共%d列\\n", col_count); while (SQLITE_ROW == sqlite3_step(stmt)) { int column0_type = sqlite3_column_type(stmt, 0); const char *column0_name = sqlite3_column_name(stmt, 0); int column0_value = sqlite3_column_int(stmt, 0); printf("col: 0 type: %d name: %-10s value: %d\\n", column0_type, column0_name, column0_value); int column1_type = sqlite3_column_type(stmt, 1); const char *column1_name = sqlite3_column_name(stmt, 1); const unsigned char *column1_value = sqlite3_column_text(stmt, 1); printf("col: 1 type: %d name: %-10s value: %s\\n", column1_type, column1_name, column1_value); int column2_type = sqlite3_column_type(stmt, 2); const char *column2_name = sqlite3_column_name(stmt, 2); int column2_value = sqlite3_column_int(stmt, 2); printf("col: 2 type: %d name: %-10s value: %d\\n", column2_type, column2_name, column2_value); int column3_type = sqlite3_column_type(stmt, 3); const char *column3_name = sqlite3_column_name(stmt, 3); const unsigned char *column3_value = sqlite3_column_text(stmt, 3); printf("col: 3 type: %d name: %-10s value: %s\\n", column3_type, column3_name, column3_value); int column4_type = sqlite3_column_type(stmt, 4); const char *column4_name = sqlite3_column_name(stmt, 4); double column4_value = sqlite3_column_double(stmt, 4); printf("col: 4 type: %d name: %-10s value: %.2f\\n", column4_type, column4_name, column4_value); printf("\\n"); } sqlite3_finalize(stmt); // char *zErrMsg = 0; // sqlite3_stmt *stmt_insert; // const char *sql_insert = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " \\ // "VALUES (5, \'Logan\', 26, \'California\', 20000.00 );"; // sqlite3_prepare_v2(db, sql_insert, -1, &stmt_insert, NULL); // if (sqlite3_step(stmt_insert) != SQLITE_DONE) { // printf("Insert Table Failed\\n"); // sqlite3_free(zErrMsg); // } // sqlite3_finalize(stmt_insert); sqlite3_close(db); return 0; }
参考资料:
sqlite3_prepare_v2 / sqlite3_exec
[转载] Sqlite c/c++ api学习
以上是关于SQLite使用的主要内容,如果未能解决你的问题,请参考以下文章
Android 逆向使用 DB Browser 查看并修改 SQLite 数据库 ( 从 Android 应用数据目录中拷贝数据库文件 | 使用 DB Browser 工具查看数据块文件 )(代码片段
SQLite 片段函数实现不会在 TextView 中将文本格式化为 HTML
java.lang.NullPointerException: Attempt to invoke virtual method ‘int android.database.sqlite异常(代码片段