首页 > 代码库 > SQLite使用(二)
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 = http://www.mamicode.com/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 = http://www.mamicode.com/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 = http://www.mamicode.com/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 = http://www.mamicode.com/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 = http://www.mamicode.com/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使用(二)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。