本章主要简示了C\C++接口的sqlite编程,包括了创建数据库文件、创建表、对数据的增删改查等。
#include "sqlite3.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void PrintSqliteResult(char** ppResult, int nRow, int nCol)
{
/**************************************************************
* 查询结果是一个一维数组,每个数组元素是一个字符串,这些字符串可分为两
* 部分:字段名以及数据记录。比如如果查询结果又三个字段,则该数据结构是
* ===========查询结果数据结构示意图=================
* col1_name, col2_name, col3_name
* col1_rec1, col2_rec1, col3_rec1
* col1_rec2, col2_rec2, col3_rec2
* ...
* =============================================
**************************************************************/
for (int i=0; i<=nRow; i++)
{
printf("%8d ", i);
for (int j=0; j<nCol; j++)
{
printf("%16s ", ppResult[i*nCol + j]);
}
printf("\n");
}
}
int main()
{
int nRet = 0;
sqlite3* db = NULL;
char** ppMsg = NULL;
char** ppResult = NULL;
srand(time(NULL));
nRet = sqlite3_open("sqlite.db", &db);
if(nRet != SQLITE_OK)
{
printf("Open sqlite file failed.\n");
goto end;
}
char szCMD[512] = {0};
// 如果表不存在则创建表
sprintf(szCMD, "CREATE TABLE IF NOT EXISTS staff(NO VARCHAR(7) PRIMARY KEY, name TEXT, age int);");
nRet = sqlite3_exec(db, szCMD, NULL, NULL, NULL);
if(nRet != SQLITE_OK)
{
printf("Create table failed.\n");
goto end;
}
// 清空表内容
sprintf(szCMD, "DELETE FROM staff;");
nRet = sqlite3_exec(db, szCMD, NULL, NULL, NULL);
if(nRet != SQLITE_OK)
{
printf("delete table content failed.\n");
goto end;
}
int nNo = 2014000;
// 插入或者替换数据记录到表
for (int i=0; i<10; i++)
{
sprintf(szCMD, "INSERT OR REPLACE INTO staff VALUES ('%d', 'name_%d', %d);", nNo+i, rand()%1024, rand()%100+10);
nRet = sqlite3_exec(db, szCMD, NULL, NULL, NULL);
if(nRet != SQLITE_OK)
{
printf("excute cmd occur error -> %s\n", szCMD);
}
}
// 查询数据
int nRow = 0;
int nCol = 0;
sprintf(szCMD, "SELECT * FROM staff ORDER BY NO;");
nRet = sqlite3_get_table(db, szCMD, &ppResult, &nRow, &nCol, ppMsg);
if(nRet != SQLITE_OK)
{
perror(*ppMsg);
goto end;
}
else
{
printf("staff table content:\n");
PrintSqliteResult(ppResult, nRow, nCol);
}
// 删除数据
sprintf(szCMD, "DELETE FROM staff WHERE age >= 80");
nRet = sqlite3_exec(db, szCMD, NULL, NULL, ppMsg);
if(nRet != SQLITE_OK)
{
perror(*ppMsg);
goto end;
}
// 更新数据记录,20岁以下匿名
sprintf(szCMD, "UPDATE staff set name='anonymous' where age < 20");
nRet = sqlite3_exec(db, szCMD, NULL, NULL, ppMsg);
if(nRet != SQLITE_OK)
{
perror(*ppMsg);
goto end;
}
// 查询数据
sprintf(szCMD, "SELECT * FROM staff ORDER BY NO;");
nRet = sqlite3_get_table(db, szCMD, &ppResult, &nRow, &nCol, ppMsg);
if(nRet != SQLITE_OK)
{
perror(*ppMsg);
goto end;
}
else
{
printf("staff table content:\n");
PrintSqliteResult(ppResult, nRow, nCol);
}
end:
sqlite3_free_table(ppMsg);
sqlite3_free_table(ppResult);
sqlite3_close(db);
return 0;
}原文地址:http://blog.csdn.net/arbboter/article/details/41864877