I am quite new in programming and aspiring to make a game using cocos2dx and sqlite. But I came across this problem where I can’t find an example on or how it can be done.
The first thing I want to do is to randomly select a row from a table which has been filtered by a range. For example there is a table with 100 rows. If I filter between the value 1 ~ 10 of Column D it resulted in 20 rows. From these 20 I want to randomly select one of them.
Secondly for that randomly selected row I want to collect 5 different value, but so far I was unable to find working example on how I can collect them.
Here is the code I try to come up with but is not working:
- Query
int MinColumnD = 1; int Max ColumnD = 10; int Dice = ( rand() % 19 ) + 1; char sql_query[100]; sprintf(sql_query, "SELECT A, B, C, D, E FROM SQList WHERE (ColumnD BETWEEN %d AND %d) ORDER BY RANDOM() LIMIT 1", MinColumnD, MaxColumnD); std::list<INFO> details; sqlite3_exec(DB, sql_query, CallBack, &details, &errorMessage);
*Thanks to CL’s comment I updated the above query to include order by random() Limit 1. However when I run it and get to the section I get this error on xcode:
Thread 1 0 sqlite3_exec 0x54cbd8: movl 60(%ebx), %eax < Thread 1: EXC_BAD_ACCESS (code=1, address=0x444e418e)
This seems to only happen when I include the ‘ORDER BY RANDOM()’ as part of the query
- Callback
int CallBack( void * pOutCount, int argc, char ** argv, char **azColName ){ std::list<Class::INFO> *pList = (std::list<Class::INFO >*)pOutCount; Class::INFO items; items._A = argv[0]; items._B = atoi(argv[1]); items._C = atoi(argv[2]); items._D = atoi(argv[3]); items._E = atoi(argv[4]); pList->push_back( items ); return 0; }
- Struct
struct Class::INFO { std::string _A; int _B; int _C; int _D; int _E; };
*Perhaps because the sqlite query is incomplete so I don’t get the result properly but I am not sure how exactly I am able to get the returned list of values from the std::list. Is it correct to think that after the query then I can just call the component inside the list to get the value like:
std::string A = details._A; int B = details._B; int C = details._C; int D = details._D; int E = details._E;
Please help!
You do not know which
rowids end up in the filtered result, so you cannot use them.To get some random records from the filtered result, first order it randomly, then take the first record of that: