//1.包含相关头文件
#include
#include
#include
int main()
{
//2.创建数据库
sqlite3 *db;
sqlite3_stmt *stat;
char *zErrMsg = 0;
char buffer2[1024 * 10]="0";
int result;
result = sqlite3_open("./MetaInfo.db", &db);
if(result)
{
printf("open failed\n");
return 1;
}
else
printf("open success\n");
result = sqlite3_exec(db, "CREATE TABLE list(fliename varchar(128) UNIQUE,imgblob);", 0, 0, &zErrMsg); //创建的list有两个参数
if(result)
printf("exec failed\n");
else
printf("exec success\n");
//由于2.bmp是一个二进制文件,所以要在使用insert语句时先用?号代替
sqlite3_prepare(db, "insert into list values ('2.bmp',?);", -1, &stat, 0);
//3.将图片插入数据库
FILE *fp;
long filesize = 0;
char * ffile;
fp = fopen("2.bmp", "rb");
if(fp != NULL)
{
//计算文件的大小
fseek(fp, 0, SEEK_END);
filesize = ftell(fp);
printf("filesize = %ld\n", filesize);
fseek(fp, 0, SEEK_SET);
ffile = (char *)malloc(filesize + 1);
size_t sz = fread(ffile, sizeof(char), filesize+1, fp);
fclose(fp);
}
//将文件数据绑定到insert语句中,替换“?”部分
sqlite3_bind_blob(stat, 1, ffile, filesize, NULL);
//执行绑定之后的SQL语句
sqlite3_step(stat);
//选取该条数据
sqlite3_prepare(db, "select * from list;", -1, &stat, 0);
sqlite3_step(stat);
//得到纪录中的BLOB字段
const void * test = sqlite3_column_blob(stat, 1);
int size = sqlite3_column_bytes(stat, 1);
sprintf(buffer2, "%s", (char *)test);
//4.导出图片
FILE *fp2;
fp2 = fopen("outfile.bmp", "wb");
if(fp2 != NULL)
{
size_t ret = fwrite(test, sizeof(char), size, fp2);
fclose(fp2);
}
free(ffile);
sqlite3_finalize(stat);
sqlite3_close(db);
return 0;
}
//首先要把2.bmp图片放在当前目录,在当前目录下生成outfile.bmp,奇怪的是outfile.bmp在ubuntu下不能打开,但在windows下却可以打开?(未深究其原因)
//把数据库导出,输入命令
sqlite3 MetaInfo.db ".dump" > MetaInfo.sql;
vi MetaInfo.sql
//可以看到如下内容:
BEGIN TRANSACTION;
CREATE TABLE list(filename varchar(128) UNIQUE,imgblob);
@
@
@
.
.
.
@
@//出现很多,不知道什么意思
INSERT INTO "list" valuses('2.bmp',X'图片的2进制数据');
COMMIT;
阅读(3056) | 评论(0) | 转发(0) |