简单介绍SQLite常用API:
int sqlite3_open( const char *filename, /* Database filename (UTF-8) */ sqlite3 **ppDb /* OUT: SQLite db handle */ ); int sqlite3_close(sqlite3*); int sqlite3_exec( sqlite3*, /* An open database */ const char *sql, /* SQL to be evaluated */ int (*callback)(void*,int,char**,char**), /* Callback function */ void *, /* 1st argument to callback */ char **errmsg /* Error msg written here */ );
一个小DEMO:
#include <stdio.h> #include <sqlite3.h> static int callback(void *NotUsed, int argc, char **argv, char **azColName) { for (int i = 0; i < argc; i++) { printf("%s = %s ", azColName[i], argv[i] ? argv[i]: "NULL"); } printf(" "); return 0; } int main(int argc, char **argv) { sqlite3 *db; int rc; rc = sqlite3_open("test.db", &db); if (rc) { printf("Can't open database: %s ", sqlite3_errmsg(db)); sqlite3_close(db); return 1; } else { printf("Open database successfully "); } char *sql; char *zErrMsg = 0; /* Create SQL statement */ sql = "CREATE TABLE COMPANY(" "ID INT PRIMARY KEY NOT NULL," "NAME TEXT NOT NULL," "AGE INT NOT NULL," "ADDRESS CHAR(50)," "SALARY REAL );"; rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); if (rc != SQLITE_OK) { printf("SQL error: %s ", zErrMsg); sqlite3_free(zErrMsg); } else { printf("Create table successfully "); } sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " "VALUES (1, 'Paul', 32, 'California', 20000.00 ); " "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " "VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); " "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" "VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );" "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" "VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );"; rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); if (rc != SQLITE_OK) { printf("SQL error: %s ", zErrMsg); sqlite3_free(zErrMsg); } else { printf("Insert Table successfully "); } sql = "SELECT * from COMPANY"; rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); if (rc != SQLITE_OK) { printf("SQL error: %s ", zErrMsg); sqlite3_free(zErrMsg); } sqlite3_close(db); return 0; }