加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

从sqlite3中读取二进制数据

发布时间:2020-12-12 20:00:11 所属栏目:百科 来源:网络整理
导读:#include stdio.h #include sqlite3.h #include stdlib.h int main( void ) { sqlite3 *db=NULL;//声明sqlite关键结构指针 char *zErrMsg = 0; int rc,id; //打开或创建一个数据库文件 rc = sqlite3_open("bind.db",db); //打开指定的数据库文件,如果不存在,
#include <stdio.h>
#include <sqlite3.h>
#include <stdlib.h>

int main( void )
{
sqlite3 *db=NULL;//声明sqlite关键结构指针
char *zErrMsg = 0;
int rc,id;
//打开或创建一个数据库文件
rc = sqlite3_open("bind.db",&db); //打开指定的数据库文件,如果不存在,将创
//建一个同名的数据库文件,需要传入db这个指针的指针,因为sqlite3_open函数要为这,个指
//针分配内存,好要让db指针指向这个内存区
if(rc!=SQLITE_OK){//或者直接是rc
fprintf(stderr,"Can't open database: %sn",sqlite3_errmsg(db));
sqlite3_close(db);
exit(1);//打开失败,退出
}
else printf("You have opened a sqlite3 database named bind.db successfully!nCongratulation! Have fun!n");
//读取二进制数据
sqlite3_stmt * stat;//sqlite 操作二进制数据需要用这个辅助的数据类型:sqlite3_stmt *
sqlite3_prepare( db,"select * from Tb1_2",-1,&stat,0 );//把 sql语句"select * from Tb1_2"解析到stat结构里去,返回值是SQLITE_OK表示成功
sqlite3_step(stat);//查询数据,返回值是SQLITE_ROW时表示成功,可以循环执行 sqlite3_step 函数,一次 step 查询出一条记录。直到返回值不为 SQLITE_ROW 时表示查询结束
id = sqlite3_column_int(stat,0);
printf("id=%dn",id);//获得字段的id值,第2个参数表示获取第几个字段内容,从0开始计算,因为我的表的ID字段是第一个字段,因此这里我填0
const void * pFileContent = sqlite3_column_blob(stat,1 );//file_content 的值,因为 file_content 是二进制,因此我需要得到它的指针,还有它的长度
printf("file_content=:%sn",pFileContent);
int len = sqlite3_column_bytes(stat,1 );
printf("len=%dn",len);
sqlite3_finalize(stat);//把 pFileContent 的内容保存出来之后,把刚才分配的内容析构掉
sqlite3_close(db);//关闭数据库
return 0;
编译和运行可执行文件:
root@cky-desktop:/home/src# gcc -o bind -l sqlite3 bind.c
root@cky-desktop:/home/src# sudo ./bind
You have opened a sqlite3 database named bind.db successfully!
Congratulation! Have fun!
id=10
file_content=:010101010101010110101010 1010101
len=31

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读