Hi,
Are there any tutorials available to explain SQLite3's prepared statement interface further? I adapted from:
http://www.linuxjournal.com/article/7803
As a test, I created a database containing a single table [children]. I filled it with the names of 3 girls and 2 boys, and then tried to write a program that selects the boys and girls separately and printed their names.
However, I have difficulty in binding text with sqlite3_bind_text()
It appears that sqlite3_step() returns SQLITE_DONE at once, so my loop to print the names never runs.
I use SQLite 3.2.0 on Windows XP. My compiler is the MinGW port of GCC 3.4.2 I used dlltool to generate libsqlite3.a
The source file used is attached as main.cpp The database name is hardcoded as "mytest.db" The SQL script that creates a chilren table is attached as children.sql
Basically I do a command line jig with: g++ -c main.cpp g++ -o test.exe main.o -lsqlite3 test
Hope someone can point out my mistakes, and point me in the right direction.
Thanks, Eugene Wee
#include <iostream> #include <sqlite3.h>
using std::cout;
using std::cerr;
using std::endl;
int main() {
sqlite3* db;
if (sqlite3_open("mytest.db", &db) == SQLITE_OK) {
sqlite3_stmt* stmt;
#define QUERY "SELECT name FROM children WHERE sex=:sex"
if (sqlite3_prepare(db, QUERY, sizeof(QUERY), &stmt, NULL) ==
SQLITE_OK) {
int index = sqlite3_bind_parameter_index(stmt, ":sex");
#define SEX "'M'"
sqlite3_bind_text(stmt, index, SEX, sizeof(SEX),
SQLITE_TRANSIENT);
cout << "The boys are:\n";
while (sqlite3_step(stmt) == SQLITE_ROW) {
cout << "- " << sqlite3_column_text(stmt, 0) <<
"\n";
}
sqlite3_reset(stmt);
#undef SEX
#define SEX "'F'"
sqlite3_bind_text(stmt, index, SEX, sizeof(SEX),
SQLITE_TRANSIENT);
cout << "The girls are:\n";
while (sqlite3_step(stmt) == SQLITE_ROW) {
cout << "- " << sqlite3_column_text(stmt, 0) <<
"\n";
}
} else {
cerr << sqlite3_errmsg(db) << endl;
}
sqlite3_finalize(stmt);
} else {
cerr << sqlite3_errmsg(db) << endl;
}
sqlite3_close(db);
return 0;
}
CREATE TABLE children(
name TEXT,
sex TEXT
);
INSERT INTO children VALUES('Amanda', 'F');
INSERT INTO children VALUES('Charis', 'F');
INSERT INTO children VALUES('Desmond', 'M');
INSERT INTO children VALUES('Bernadette', 'F');
INSERT INTO children VALUES('Charles', 'M');

