Sqlite読み書きblobデータ(c++)

1623 ワード


#include
#include
#include

using namespace std;

int main()
{
	sqlite3 *db;
	sqlite3_stmt *stat;
	char *zErrMsg = 0;

	char buffer2[1024] = "0";


	sqlite3_open("./MetaInfo.db", &db);
	int result;

	if (result)
	{
		cout << "Open the database sqlite.db failed" << endl;
	}

	else
		cout << "Open the database sqlite.db sucessfully" << endl;

	sqlite3_exec(db, "CREATE TABLE list (fliename varchar(128) UNIQUE, fzip blob);", 0, 0, &zErrMsg);
	sqlite3_prepare(db, "insert into list values ('./data/2.bmp',?);", -1, &stat, 0);

	FILE *fp;
	long filesize = 0;
	char * ffile;

	fp = fopen("./data/2.bmp", "rb");

	if (fp != NULL)
	{
		fseek(fp, 0, SEEK_END);
		filesize = ftell(fp);
		fseek(fp, 0, SEEK_SET);

		ffile = new char[filesize + 1];
		size_t sz = fread(ffile, sizeof(char), filesize + 1, fp);

		fclose(fp);
	}

	sqlite3_bind_blob(stat, 1, ffile, filesize, NULL);
	sqlite3_step(stat);

	sqlite3_prepare(db, "select * from list;", -1, &stat, 0);
	sqlite3_step(stat);

	const void * test = sqlite3_column_blob(stat, 1);
	int size = sqlite3_column_bytes(stat, 1);

	sprintf(buffer2, "%s", test);

	FILE *fp2;

	fp2 = fopen("outfile.png", "wb");

	if (fp2 != NULL)
	{
		size_t ret = fwrite(test, sizeof(char), size, fp2);
		fclose(fp2);
	}

	delete(ffile);
	sqlite3_finalize(stat);
	sqlite3_close(db);
	return 0;
}

参照先:https://www.cnblogs.com/wengzilin/archive/2012/03/28/2420796.html