【发布时间】:2012-12-20 19:54:56
【问题描述】:
我制作了自己的数据库格式,遗憾的是它需要太多的内存,而且它的大小变得非常可怕,而且维护起来也很糟糕。
所以我正在寻找一种将对象中的结构数组存储到表中的方法。
我猜我需要使用 blob,但欢迎使用所有其他选项。实现 blob 的简单方法也会有所帮助。
我已经附上了我的保存代码和相关结构(从我之前可怕的帖子更新)
#include "stdafx.h"
#include <string>
#include <stdio.h>
#include <vector>
#include "sqlite3.h"
using namespace std;
struct PriceEntry{
float cardPrice;
string PriceDate;
int Edition;
int Rarity;
};
struct cardEntry{
string cardName;
long pesize;
long gsize;
vector<PriceEntry> cardPrices;
float vThreshold;
int fav;
};
vector<cardEntry> Cards;
void FillCards(){
int i=0;
int j=0;
char z[32]={0};
for(j=0;j<3;j++){
cardEntry tmpStruct;
sprintf(z, "Card Name: %d" , i);
tmpStruct.cardName=z;
tmpStruct.vThreshold=1.00;
tmpStruct.gsize=0;
tmpStruct.fav=1;
for(i=0;i<3;i++){
PriceEntry ss;
ss.cardPrice=i+1;
ss.Edition=i;
ss.Rarity=i-1;
sprintf(z,"This is struct %d", i);
ss.PriceDate=z;
tmpStruct.cardPrices.push_back(ss);
}
tmpStruct.pesize=tmpStruct.cardPrices.size();
Cards.push_back(tmpStruct);
}
}
int SaveCards(){
// Create an int variable for storing the return code for each call
int retval;
int CardCounter=0;
int PriceEntries=0;
char tmpQuery[256]={0};
int q_cnt = 5,q_size = 256;
sqlite3_stmt *stmt;
sqlite3 *handle;
retval = sqlite3_open("sampledb.sqlite3",&handle);
if(retval)
{
printf("Database connection failed\n");
return -1;
}
printf("Connection successful\n");
//char create_table[100] = "CREATE TABLE IF NOT EXISTS users (uname TEXT PRIMARY KEY,pass TEXT NOT NULL,activated INTEGER)";
char create_table[] = "CREATE TABLE IF NOT EXISTS Cards (CardName TEXT, PriceNum NUMERIC, Threshold NUMERIC, Fav NUMERIC);";
retval = sqlite3_exec(handle,create_table,0,0,0);
printf( "could not prepare statemnt: %s\n", sqlite3_errmsg(handle) );
for(CardCounter=0;CardCounter<Cards.size();CardCounter++){
char Query[512]={0};
for(PriceEntries=0;PriceEntries<Cards[CardCounter].cardPrices.size();PriceEntries++){
//Here is where I need to find out the process of storing the vector of PriceEntry for Cards then I can modify this loop to process the data
}
sprintf(Query,"INSERT INTO Cards VALUES('%s', %d, %f, %d)",
Cards[CardCounter].cardName.c_str(),
Cards[CardCounter].pesize,
Cards[CardCounter].vThreshold,
Cards[CardCounter].fav); //My insert command
retval = sqlite3_exec(handle,Query,0,0,0);
if(retval){
printf( "Could not prepare statement: %s\n", sqlite3_errmsg(handle) );
}
}
// Insert first row and second row
sqlite3_close(handle);
return 0;
}
我尝试使用谷歌搜索,但结果还不够。
【问题讨论】:
-
如果您至少提供一小部分“您目前拥有的”,那就太好了。我可以建议您开始使用具有某种含义的变量名称吗?我确定您知道 E、R 和 cP 代表什么,但没有其他人知道。它们不必是很长的名称,只需 3-5 个字符。
-
(只是猜测)那么你是否将'cEy'元素存储在'cEy'表的不同sqlite列中,你的问题是如何在sqlite列中实际存储'PE'值数组?如果是这样,那么您需要一种方法来“序列化”一个 PE(以及它们的向量),然后将序列化数据存储为 BLOB 列。
-
@MatsPetersson 代码已更新 :) @Gigi 如果我必须走 blob 路线,我会将所有信息放入带有标题的字符缓冲区中,以便区分条目。从来不需要序列化,所以不确定它在代码方面意味着什么。我希望 SQL 有某种更简单的方法。
-
“序列化”只是将某些内容转换为可以存储在某处的“表示”。对于像您这样的简单情况,并且忽略字节顺序,您只需将 pod PE 成员的二进制表示附加到 char 向量,加上字符串“PriceDate”大小,然后是该字符串中的每个字符。然后将其写入blob列。同样对于反序列化,只需执行与此相反的操作。