Sqlite库的基本操作

Sqlite 基本操作


打开数据库

sqlite3* SQ_DB;
char *zErrMsg = 0; int nRes = sqlite3_open("test.db", &SQ_DB);
if (nRes!=SQLITE_OK)
{
return -1;
}

执行sql语句

/* Create SQL statement */
std::string sql = "CREATE TABLE COMPANY(" \
"ID INT PRIMARY KEY NOT NULL," \
"NAME TEXTNOT NULL," \
"AGEINT NOT NULL," \
"ADDRESSCHAR(50)," \
"SALARY REAL );"; /* Execute SQL statement */
nRes = sqlite3_exec(SQ_DB, sql.c_str(), 0, 0, 0); if (nRes != SQLITE_OK){
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
else{
fprintf(stdout, "Table created successfully\n");
}

查询结果

  • 回调方式

      static int callback(void *NotUsed, int argc, char **argv, char **azColName)
    {
    int i;
    for (i = 0; i < argc; i++)
    {
    printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
    }
    printf("\n");
    return 0;
    }
  • TABLE方式

      char **dbResult;
    int nRow = 0;
    int nColumn = 0;
    sql = "SELECT * FROM COMPANY";
    int result = sqlite3_get_table(SQ_DB, sql.c_str(), &dbResult, &nRow, &nColumn, 0); string strLine;
    for (int i=1; i<=nRow; i++)
    {
    for (int j = 0; j<nColumn; j++)
    {
    strLine = dbResult[i*nColumn + j];
    cout << setw(10) <<strLine;
    }
    cout<< endl; }
    if (dbResult)
    {
    sqlite3_free_table(dbResult);
    }

关闭数据库

sqlite3_close(SQ_DB);
上一篇:玩转Web之Jsp(一)-----jsp中的静态包含(<%@include file="url"%>)与动态包含(


下一篇:无锁编程(五) - RCU(Read-Copy-Update)