1 打开数据库文件

  sqlite3* m_db = NULL;

  int ret = sqlite3_open_v2("test.db", &db, SQLITE_OPEN_READWRITE, NULL);

  if (ret != SQLITE_OK)

  {

    return;

  }


2 如果表不存在,创建表

char szCreateUserDataSql[1024] = "create table if not exists tb_user (id INTEGER ,\

    type INTEGER,\

    kind INTEGER)";


3 创建唯一的主键ID

char szCreateUserDataSql[1024] = "create table if not exists tb_user (id INTEGER PRIMARY KEY AUTOINCREMENT,\

    type INTEGER,\

    kind INTEGER)";


4 查询

  char szSql[1024] = {0};

  sprintf(szSql, "select distinct * from tb_test");

  sqlite3_stmt* stmt = NULL;

  sqlite3_prepare(m_db, szSql, -1, &stmt, 0);

  while (sqlite3_step(stmt) == SQLITE_ROW)

  {

    const unsigned char*  szPOIName = sqlite3_column_text(stmt, 0);

    char szName[128] = {0};

    if (szPOIName)

    {

      sprintf(szName, "%s", szPOIName);

    } 

    int kx = sqlite3_column_int(stmt, 3);

    float x = sqlite3_column_double(stmt, 5);

  }

  sqlite3_finalize(stmt);


5 获取sql执行失败的错误信息

char* errMsg = NULL;

char* szSql = "select * from address";

nRet = sqlite3_exec(pDB, szSql, NULL, NULL ,&errMsg);

if (nRet != SQLITE_OK)

{

   cout<<errMsg<<endl;

   sqlite3_free(errMsg);

}

注意:释放errMsg指向的内存

6 关闭数据库

  sqlite3_close(db);