当我在开发一个项目时,发现当数据库中存入了较多的信息时,我们要读每条数据然后处理删除时,我会用select 语句来逐一读取,但这样有个弊端就是我需要自己来维护这个id值,这样就是得代码变得更加复杂,可重入性大大降低。但是sqlite3还是给我们提供了很多便利,我们可以通过只读取第一条数据方法来让数据库自己来维护这个id值,这样就是得了我们的代码精简了很多,而且代码的可重入性也有了比较乐观的改善。
话不多说上函数:
#include "init_db.h"
/* 创建数据库 */
sqlite3 * sqlite_create();
/* 将数据写入数据库 */
int write_db(sqlite3 *db, tlv_buf_t *tlv);
/* 从数据库中删除已经发送成功的数据 */
int rm_tlvda_db(sqlite3 *db, int db_id);
/* 从数据库中读取数据 */
unsigned short read_db_data(sqlite3* db,s_db_data* s_data);
/* 数据库的callback函数 */
inline int callback(void* para, int f_num, char ** f_value,char** f_name);
sqlite3 * sqlite_create()
{
sqlite3* db = NULL;
const char* sql_create = "create table if not exists temp(id integer PRIMARY KEY autoincrement,tlv_data blob)";
if (access(DB_PATHNAME, F_OK) != 0) //判断数据库文件是否存在
{
if (sqlite3_open(DB_PATHNAME, &db) != SQLITE_OK)
{
printf("Open sqlite error:%s\n", sqlite3_errmsg(db));
return ;
}
else
{
printf("Open sqlite success.\n");
}
if (sqlite3_exec(db, sql_create, NULL, NULL, NULL)!= SQLITE_OK)
{
printf("Create table error:%s\n", sqlite3_errmsg(db));
return ;
}
}
if (sqlite3_open(DB_PATHNAME, &db) != SQLITE_OK) //数据库文件存在则直接打开数据库文件
{
printf("Open sqlite error:%s\n", sqlite3_errmsg(db));
return ;
}
if (sqlite3_exec(db, sql_create, NULL, NULL, NULL)!= SQLITE_OK)
{
printf("Create table error:%s\n", sqlite3_errmsg(db));
return ;
}
return db;
}
int write_into_db(sqlite3 *db, tlv_buf_t *tlv)
{
char sql_insert[64] = {0};
sqlite3_stmt *stmt = NULL;
memset(sql_insert, 0, 64);
snprintf(sql_insert, 64, "insert into temp values(null,?);");
sqlite3_prepare(db, sql_insert, strlen(sql_insert),&stmt,0);
{
sqlite3_bind_blob(stmt, 1, &tlv->buf, tlv->len,NULL);
sqlite3_step(stmt);
}
sqlite3_finalize(stmt);
return 0;
}
unsigned short read_db_data(sqlite3* db,s_db_data* s_data)
{
char sql_select[64] = "select tlv_data from temp limit 1";
char sql_id[64] = "select * from temp limit 1";
unsigned short first_id = -1; //需要获取的id变量
sqlite3_stmt *pstmt = 0;
if (sqlite3_exec(db, sql_select, callback, s_data, NULL)!= SQLITE_OK)
{
printf("select data from db error.\n");
return -1;
}
if( (sqlite3_prepare(db, sql_id, strlen(sql_id), &pstmt, NULL)) != SQLITE_OK )
{
printf("sqlite3_prepare error ! \n");
return -1;
}
sqlite3_step(pstmt);
/* 读取整形数据 第一个数据的ID */
first_id = sqlite3_column_int(pstmt,0);
sqlite3_finalize(pstmt);
return first_id;
}
/* 回调函数 */
int callback(void* para, int f_num, char ** f_value,char** f_name)
{
s_db_data * db_da = (s_db_data* )para;
memset(db_da->buf, 0, db_da->len);
memcpy(&db_da->buf, *f_value, db_da->len);
return 0;
}
/* 从数据库中删除已经发送成功的数据 */
int rm_tlvda_db(sqlite3 *db, int db_id)
{
char sql[64] = {0};
snprintf(sql,64,"delete from temp where id = %d",db_id);
if (sqlite3_exec(db, sql,NULL, NULL, NULL)!= SQLITE_OK)
{
printf("rm db da error.\n");
}
}