SQL / C++ Tutorial using sqlwrapped
7. Reading many rows from a database table
PreviousNextIndex
To read any number of rows from a database table, the Query class
have the methods get_result(), fetch_row() and free_result(). The return
value for get_result() is a pointer to the result set or NULL if the
query fails. There is no need to use this pointer directly, as the example
will clearly show.
The fetch_row() method returns a value != 0 as long as a valid row was
fetched from the result set.
Finally, free_result() must be called to release the query for another use.
To access values from the result set, the following methods are valid after
a call to fetch_row() has returned anything else than 0; getstr() returns a
string value, getval() / getuval() returns signed / unsigned integer values,
getbigint() / getubigint() return 64-bit signed / unsigned integer values,
and getnum() returns floating point numbers.
The order of the method calls is important, as the first field is returned
first, then the next etc.
Each of the data access methods can also be called with a zero-based field
index number to directly access any field from the query.
example
int main()
{
StderrLog log;
Database db("localhost", "root", "", "tutorialdb", &log); // MySQL specific
if (!db.Connected())
{
printf("Database not connected - exiting\n");
exit(-1);
}
Query q(db);
q.get_result("select * from player");
while (q.fetch_row())
{
long num = q.getval();
std::string name = q.getstr();
printf("#%ld: %s\n", num, name.c_str());
}
q.free_result();
}
example5_mysql.cppexample5_sqlite3.cpp
PreviousNext