IAM

OPENSOURCEFAN STUDYING
STUDYINGCOMPUTERSCIENCEANDMATH COMPUTERSCIENCE

Check out the latest superpixel benchmark — Superpixel Benchmark (2016) — and let me know your opinion! @david_stutz
07thJANUARY2017

SNIPPET

C++

Example demonstrating how to use SQLiteCpp for working with SQLite databases from C++.

main.cpp
#include <fstream>
#include <vector>
#include <iostream>
#include <SQLiteCpp/SQLiteCpp.h>

std::string getCreateTableQuery()
{
    std::string query = 
            "CREATE TABLE students ("
                "id INT NOT_NULL,"
                "name VARCHAR(255),"
                "gpa DECIMAL(1, 2),"
                "PRIMARY KEY(id)"
            ");";
    
    return query;
}

void getInsertQueries(std::vector<std::string> &queries)
{
    queries.push_back("INSERT INTO students (id, name, gpa) VALUES (1, \"David\", 4.00);");
    queries.push_back("INSERT INTO students (id, name, gpa) VALUES (2, \"Tobias\", 4.00);");
}

std::string getSelectQuery()
{
    std::string query = 
            "SELECT * FROM students;";
    
    return query;
}

int main(int argc, char** argv) {
    
    try
    {
        bool dbFound = static_cast<bool>(std::ifstream("example.db3", std::ifstream::in | std::ifstream::binary));
        
        if (!dbFound)
        {
            std::cout << "example.db3 not found, creating students table." << std::endl;
            SQLite::Database db("example.db3", SQLite::OPEN_READWRITE|SQLite::OPEN_CREATE);
            
            SQLite::Statement createQuery(db, getCreateTableQuery());
            createQuery.exec();
            
            std::vector<std::string> insertQueries;
            getInsertQueries(insertQueries);
            
            for (unsigned int i = 0; i < insertQueries.size(); i++)
            {
                SQLite::Statement insertQuery(db, insertQueries[i]);
                insertQuery.exec();
            }
        }
        else
        {
            std::cout << "example.db3 found." << std::endl;
            SQLite::Database db("example.db3");
            SQLite::Statement query(db, getSelectQuery());
            
            while(query.executeStep())
            {
                std::cout << query.getColumn("id") << "," << query.getColumn("name") 
                        << "," << query.getColumn("gpa") << std::endl;
            }
        }
    }
    catch (std::exception& e)
    {
        std::cout << "exception: " << e.what() << std::endl;
    }
    
    return 0;
}

What is your opinion on the code snippet? Is it working? Let me know your thoughts in the comments below or using the following platforms: