您的位置:首页 > 数据库

sqlite3基本操作

2016-01-02 21:48 351 查看
string path = "device.db";
sqlite3 *pDB;
sqlite3_stmt *stmt;
char *errMsg;
if(!Utility::isFileORDirExist(path))
{//判断数据库文件是否已经存在,不存在是创建数据库和数据库表
int res = sqlite3_open(path.c_str(), &pDB);
if(res != SQLITE_OK)
{
MGLogD("device db open fail");
sqlite3_close(pDB);
return;
}
string sql = "create table device(name text, address text);";
res = sqlite3_exec(pDB, sql.c_str(), 0, 0, &errMsg);
sqlite3_close(pDB);
}
//打开数据库
int res = sqlite3_open(path.c_str(), &pDB);
if(res != SQLITE_OK)
{
MGLogD("device db open fail");
sqlite3_close(pDB);
return;
}
//数据库插入操作
string name = "Test01";
string address = "23:3d:34:8f:89";
string np1 = "insert into device values('" + name +"','"+ address + "');";
name = "Test02";
address = "23:3d:34:8d:89";
string np2= "insert into device values('" + name +"','"+ address + "');";
res = sqlite3_exec(pDB, np1.c_str(),0,0, &errMsg);
res = sqlite3_exec(pDB, np2.c_str(),0,0, &errMsg);
res = sqlite3_exec(pDB,"commit transaction;",0,0, &errMsg);
//数据库查询
int row = 0, column = 0;
char **result;
string sql = "select * from device;";
res = sqlite3_get_table(pDB, sql.c_str(), &result, &row, &column, &errMsg);
int i = 0;
for(i = column; i < (row + 1) * column; i ++)
cout << result[i];
sqlite3_free_table(result);
sqlite3_close(pDB);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  sqlite3 c++