16,547
社区成员




//创建并打开文件
MySQLite *sqlite = new MySQLite;
sqlite->sqlite_connect(TEST_FILE);
Sleep(100);
//建立一张表
std::string str_sql = "CREATE TABLE ";
str_sql += TEMP_TABLE;
str_sql += "(name VARCHAR, data blob);";
bool b = sqlite->sqlite_exec(str_sql.c_str());
assert_exp(b == true);
//------------------------------------------------------------------------------------
//写数据
//把一个 sql 语句解析到 stat 结构里去
sqlite3_stmt *stat;
std::string table_name = TEMP_TABLE;
std::string line_name = "san";
str_sql = "UPDATE '" + table_name + "' SET data = ? WHERE name = '" + line_name + "';";
int result = sqlite3_prepare( sqlite->m_db, str_sql.c_str(), -1, &stat, 0 );
assert_exp(result == SQLITE_OK && stat != NULL );
//将结构体转化为二进制字符串流
st_tb tb;
tb.a = 5;
std::string str_binary = ToStringEasyBin(tb);
//开始插入二进制数据
int back = sqlite3_bind_blob( stat, 1, str_binary.c_str(), str_binary.length(), NULL );
//保存到数据库里
result = sqlite3_step( stat );
//释放结构
sqlite3_finalize( stat );
//------------------------------------------------------------------------------------
//读数据
sqlite3_stmt * stat1;
str_sql = "select * from ";
str_sql += TEMP_TABLE;
result = sqlite3_prepare( sqlite->m_db, str_sql.c_str(), -1, &stat1, 0 );
assert_exp(result == SQLITE_OK );
result = sqlite3_step( stat1 );
if (result != SQLITE_ROW)
{
std::cout<< "fail"<<endl;
return 0;
}
const void *content = sqlite3_column_blob( stat1, 1 );
int len = sqlite3_column_bytes( stat1, 1 );
char *src = (char*)content;
std::string desc(src,len);
//将字符串流转化为原结构
st_tb tb1;
ToStructEasyBin(desc,tb1);
//把刚才分配的内容析构掉
sqlite3_finalize( stat1 );