C++ 程序中如何输出sqlite3数据库表的内容

本次博客所写建立在数据库food.db中fruit表

fruit表的创建规则为 create fruit (id integer primary key,name text);

里面共有三条数据

id name
1 banana
2 apple
3 pear

 

这边提供两种方法从里面获取内容:

方法1:sqlite3_exex函数利用回调函数callback来获得数据库中表的内容

#include 
#include 
using namespace std;
sqlite3 * db;
int callback(void * para,int columnCount,char ** columnValue,char ** columnName)
{
    if(columnCount ==0)//查询语句在表中未查到记录
    {
        return 0;
    }
    for(int i = 0;i < columnCount; i++)
    {
        cout << columnName[i] << " " << columnValue[i] <

输出结果为 :

id 1
name banana
id 2
name apple
id 3
name pear

方法2:

#include 
#include 
#include 
using namespace std;
int SelectRecord(sqlite3 *db,const std::string & strSql)
{
    if(db == NULL)
    {
        return 0;
    }
    sqlite3_stmt *pVM = NULL;
    int ret = SQLITE_OK;
    sqlite3_busy_handler(db,strSql.c_str(),-1,&pVM,0);
    if(ret != SQLITE_OK)
    {
        return -1;
    }
    int colCount = sqlite3_column_count(pVM);
    for(int i = 0;i < colCount ;i++)
    {
        char * pColName = (char *)sqlite3_column_name(pVM,i);
        cout << pColName << " "; 
    }
    cout << endl;
    while(sqlite3_step(pVM) == SQLITE_ROW)
    {
        for(int i = 0;i < colCount;i++)
        {
            std::string strTemp;
            char * pColValue = (char *)sqlite3_column_text(pVM,i)
            int columnLen =0;
            if(pColValue !=NULL)
            {
                    columnLen = sqlite3_column_byte(pVM,i);
            }
            strTemp.append((char *)pColValue,columnLen);
            cout << strTemp << " ";
        }
        cout << endl;
    }
    sqlite3_finalize(pVM);
    pVM = NULL;
    return 0;
}
int main()
{
    int ret = sqlite3_open("food.db",&db);
    if(ret == SQLITE_OK)
    {
        SelectRecord(db,"select * from fruit");
    }
    sqlite3_close(db);
    return 0;
}

输出结果为:

id name
1 banana
2 apple
3 pear

 

你可能感兴趣的:(sqlite3数据库)