int sqliteOperate(string file, int id, string name, double weight)
{
// 连接数据库
sqlite3_open(file, &m_db);
// 数据库操作
/* 第一种就是sqlite3_exec函数,这种方法一般使用在不返回数据集的情况,
也就是说少用于查询类的操作,一般使用其来创建表结构、更新、插入或者删除操作。*/
int sqlite3_exec(sqlite3*, const char *sql, int(*callback)(void*,int,char**,char**), void *, char **errmsg);
/* 第二种就是使用sqlite3_prepare_v2和sqlite3_step两个函数搭配着进行操作。其中sqlite3_prepare_v2是一个将SQL语句编译为sqlite内部一个结构体(sqlite3_stmt)。该结构体中包含了将要执行的SQL语句的信息。
而sqlite3_step则是让转化后的SQL进行下一步的操作。因此通过这两个函数可以很方便地获取到数据库中的数据。*/
int sqlite3_prepare_v2(sqlite3 *db, const char *zSql, int nByte, sqlite3_stmt **ppStmt, const char **pzTail);
// 创建表
int ret = sqlite3_exec(m_db, "create table if not exists table_name(id int, name text, weight double, primary key(id))", nullptr, nullptr, nullptr);
sqlite3_step(stmt);
// 新增数据
// 当一个表中存在主键或唯一索引时,你使用replace into 语句插入数据时,会先把冲突的旧数据删除,然后插入新数据。而insert into则会报错。其他情况与insert into一样。
ret = sqlite3_prepare(m_db, "replace into table_name (id, name, weight) values(?, ?, ?)", -1, &stmt, 0);
sqlite3_bind_int(stmt, 1, id);
sqlite3_bind_text(stmt, 2, name, name.length(), nullptr);
sqlite3_bind_double(stmt, 3, weight);
ret = sqlite3_step(stmt);
sqlite3_finalize(stmt);
// 删除数据
ret = sqlite3_prepare(m_db, "delete from table_name where id=?", -1, &stmt, 0);
sqlite3_bind_int(stmt, 1, id);
ret = sqlite3_step(stmt);
sqlite3_finalize(stmt);
// 修改数据
ret = sqlite3_prepare(m_db, "update table_name set name=? where id=?", -1, &stmt, 0);
sqlite3_bind_text(stmt, 1, name);
sqlite3_bind_int(stmt, 2, id);
ret = sqlite3_step(stmt);
sqlite3_finalize(stmt);
// 查找(获取)数据
// SELECT语句中使用ALL或DISTINCT选项来显示表中符合条件的所有行或删除其中重复的数据行,默认为ALL。使用DISTINCT选项时,对于所有重复的数据行在SELECT返回的结果集合中只保留一行。
ret = sqlite3_prepare(m_db, "select * from table_name where id = ?", -1, &stmt, 0);
sqlite3_bind_int(stmt, 1, id);
ret = sqlite3_step(stmt);
if (ret == SQLITE_ROW)
{
id = sqlite3_column_int(stmt, 0);
name = (const char*)sqlite3_column_text(stmt, 1);
weight = (double)sqlite3_column_double(stmt, 2);
}
sqlite3_finalize(stmt);
// 关闭数据库
sqlite3_close(m_db);
}