说实话,用代码实现sqlite3查看数据库中有哪些表我还真的没找到现成资源,网上提供的语句还真用不了,而且大多都是命令行语句,由于的做的MFC项目要用到这个功能,特意学习了下,下面分享我的成果,希望可以帮到你.
环境:VS2005
#include "sqlite3.h"
#include <iostream>
#include "string.h"
#pragma comment(lib,"sqlite_win32_dll.lib")
using namespace std;
int main()
{
sqlite3 * datb = NULL; //要定义全局变量
int ret = sqlite3_open("demo.db",&datb);
if(ret == SQLITE_OK)
{
cout << "demo.db打开成功!" << endl;
}
else
{
cout << "demo.db打开失败!" << endl;
return 0;
}
char * errmsg; //要定义全局变量
char str3[1024] = {"create table "};
char * str11 = "List";
strcat(str3,str11);
char *str2 = "(id int primary key,name text)";
strcat(str3,str2);
char sql[1024] = {0};
sprintf(sql,"drop table if exists %s",str11);
sqlite3_exec(datb,sql,NULL,NULL,&errmsg); //在创建表时,如果表存在,则删除
ret = sqlite3_exec(datb,str3,NULL,NULL,&errmsg);
if(ret == SQLITE_OK)
{
cout << "demoF表创建成功!" << endl;
}
//插入记录
const char * str7 = "insert into demoF values(1,'zhang')";
const char * str8 = "insert into demoF values(2,'li')";
const char * str9 = "insert into demoF values(3,'wang')";
const char * str10 = "insert into demoF values(4,'cheng')";
sqlite3_exec(datb,str7,NULL,NULL,&errmsg);
sqlite3_exec(datb,str8,NULL,NULL,&errmsg);
sqlite3_exec(datb,str9,NULL,NULL,&errmsg);
sqlite3_exec(datb,str10,NULL,NULL,&errmsg);
//查询表
char **dbresult;
int j,nrow,ncolumn,index = 0;
//ret = sqlite3_get_table(datb,"select name from demo.db where type='U' and name like '%demo%' ",&dbresult,&nrow,&ncolumn,&errmsg);
//ret = sqlite3_get_table(datb,"select * from all_tables ",&dbresult,&nrow,&ncolumn,&errmsg);
//ret = sqlite3_get_table(datb,"select name from demo.db where type='table' order by name ",&dbresult,&nrow,&ncolumn,&errmsg);
ret = sqlite3_get_table(datb,"select name from sqlite_master where type ='table'order by name ",&dbresult,&nrow,&ncolumn,&errmsg);
if(ret == SQLITE_OK)
{
for(int i = 0;i <= nrow; i++)
/*for(j = 0;j < ncolumn;j++)*/
{
cout << dbresult[index] << endl;
index++;
}
cout << nrow << ncolumn << endl;
}
可以看看我试了多少种语句(只有最后一个是有用的)
运行结果
这个结果可以看出表在存的时候是2行1列,那个name是名字提示,下面的List,demoF才是表的真正名字.
如果你能看到我发的博客,那么你还算幸运因为我被这个功能卡了三个星期(主要是网上资源太乱,而且没有代码实现方法,难受)