Example: Work with SQLite3 databases
Demonstrates how to work with SQLlite3 databases.
SQLite3 functions are defined in lib/sqlite3.inc.v1
Note: You have to install SQLite3 libraries. On Windows copy the 32-Bit DLL sqlite3.dll into the home directory of V1 where v1.exe is located.
https://www.sqlite.org/download.html
<?v1
require_once ("lib/sqlite3.inc.v1");
// Open database
db = null;
sqlite3_open ("test.db", db);
if (!db) {
print ("Cannot open database");
exit (1);
}
// Insert data
sql =
"DROP TABLE IF EXISTS Cars;".
"CREATE TABLE Cars(Id INT, Name TEXT, Price INT);".
"INSERT INTO Cars VALUES(1, 'Audi', 52642);".
"INSERT INTO Cars VALUES(2, 'Mercedes', 57127);".
"INSERT INTO Cars VALUES(3, 'Skoda', 9000);".
"INSERT INTO Cars VALUES(4, 'Volvo', 29000);".
"INSERT INTO Cars VALUES(5, 'Bentley', 350000);".
"INSERT INTO Cars VALUES(6, 'Citroen', 21000);".
"INSERT INTO Cars VALUES(7, 'Hummer', 41400);".
"INSERT INTO Cars VALUES(8, 'Volkswagen', 21600);";
err_msg = "";
rc = sqlite3_exec (db, sql, null, null, err_msg);
print ("Last rowid = ", sqlite3_last_insert_rowid (db));
if (rc != SQLITE_OK ) {
print ( "Error (".rc."):", err_msg);
sqlite3_close(db);
exit (1);
}
// Select data with prepared statement
stmt = 0;
sql = "SELECT Id, Name, Price FROM Cars WHERE Id = @id";
rc = sqlite3_prepare (db, sql, -1, stmt);
if (rc == SQLITE_OK)
{
paramIdx = sqlite3_bind_parameter_index (stmt, "@id");
sqlite3_bind_int (stmt, paramIdx, 3); // Bind integer value 3 to parameter
// Print column names
colCnt = sqlite3_column_count (stmt);
for (i=0;i<colCnt;i++)
printf("%s|", sqlite3_column_name (stmt, i));
print ("\r\n");
// Print rows
while (sqlite3_step(stmt) != SQLITE_DONE) {
for (i=0;i<colCnt;i++)
printf("%s|", sqlite3_column_text (stmt, i));
print ("\r\n");
}
}
else {
print ( "Error (".rc."):", sqlite3_errmsg(db));
sqlite3_close(db);
exit (1);
}
sqlite3_finalize (stmt);
sqlite3_close(db);
?>