SQL / C++ Tutorial using sqlwrapped
4. Reading a single field from a database table
PreviousNextIndex
The Query class is used to manipulate data in the database. Each instance
of the Query class is one connection to the database. The only parameter
given in the Query class constructor is a reference to the Database instance
that the Query class use to connect to the database.
There are a few methods in the Query class specifically used to read single
field values from a table. The methods are get_string() to read strings,
get_count() to read integer values, and get_num() to read floating point numbers.
All the methods take a string containing the sql query as input parameter.
MySQL example
#include <libmysqlwrapped.h>
int main()
{
Database db("localhost", "root", "", "tutorialdb");
if (!db.Connected())
{
printf("Database not connected - exiting\n");
exit(-1);
}
Query q(db);
std::string name = q.get_string("select name from player where num=1");
long num = q.get_count("select num from player where name='Grymse'");
printf("The name of player#1 is '%s'\n", name.c_str());
printf("The number of 'Grymse' is %ld\n", num);
}
example2_mysql.cpp
sqlite3 example
#include <libsqlitewrapped.h>
int main()
{
Database db("tutorial.db");
if (!db.Connected())
{
printf("Database not connected - exiting\n");
exit(-1);
}
Query q(db);
std::string name = q.get_string("select name from player where num=1");
long num = q.get_count("select num from player where name='Grymse'");
printf("The name of player#1 is '%s'\n", name.c_str());
printf("The number of 'Grymse' is %ld\n", num);
}
example2_sqlite3.cpp
PreviousNext