Overview
Examples
Screenshots
Comparisons
Applications
Download
Documentation
Tutorials
Bazaar
Status & Roadmap
FAQ
Authors & License
Forums
Funding Ultimate++
Search on this site













SourceForge.net Logo

SQL Tutorial


Table of contents

 

1. SqlSession, Sql, opening database connection

2. Using global main database, executing statements with parameters, getting resultset info

3. Using SqlExp

4. Schema file

5. Using schema file to define SqlId constants

6. Using structures defined by schema files

 


1. SqlSession, Sql, opening database connection

SqlSession derived objects represent database connection. Each SQL database (Sqlite3, Microsoft SQL, Oracle, MySQL, PostgreSQL) has its own session class derived from SqlSession. Sql class is used to issue SQL statements and retrieve results:

 

#include <Core/Core.h>

#include <plugin/sqlite3/Sqlite3.h>

 

using namespace Upp;

 

CONSOLE_APP_MAIN

{

    Sqlite3Session sqlite3;

    if(!sqlite3.Open(ConfigFile("simple.db"))) {

        Cout() << "Can't create or open database file\n";

        return;

    }

    

#ifdef _DEBUG

    sqlite3.SetTrace();

#endif

 

    Sql sql(sqlite3);

    sql.Execute("select date('now')");

    while(sql.Fetch())

        Cout() << sql[0] << '\n' << ;

}

 

In this tutorial, we are using Sqlite3 database. The connection method varies with database; in this case it is done using Open statement.

SetTrace is useful in debug mode - all issued SQL statements and SQL errors are logged in standard U++ log.

Each Sql instance has to be associated to some SqlSession - it is passed as constructor parameter (parameter-less Sql constructor uses global session, more on that in section 2.). To execute SQL statements, use Execute. If executed statement is Select, it may return a result set, which is retrieved using Fetch. Columns of result set are then accessed by Sql::operator[] using index of column (starts with 0). Values are returned as Value type.

 


2. Using global main database, executing statements with parameters, getting resultset info

Most applications need to work with just single database backend, therefore repeating SqlSession parameter in all Sql declarations would be tedious.

To this end U++ supports concept of "main database" which is represented by SQL variable. SQL is of Sql type. When any other Sql variable is created with default constructor (no session parameter provided), it uses the same session as the one the SQL is bound to. To assign session to global SQL, use operator=:

#include <Core/Core.h>

#include <plugin/sqlite3/Sqlite3.h>

 

using namespace Upp;

 

CONSOLE_APP_MAIN

{

    Sqlite3Session sqlite3;

    if(!sqlite3.Open(ConfigFile("simple.db"))) {

        Cout() << "Can't create or open database file\n";

        return;

    }

    

#ifdef _DEBUG

    sqlite3.SetTrace();

#endif

 

    SQL = sqlite3;

    

    SQL.Execute("drop table TEST");

    SQL.ClearError();

    SQL.Execute("create table TEST (A INTEGER, B TEXT)");

 

    for(int i = 0; i < 10; i++)

        SQL.Execute("insert into TEST(A, B) values (?, ?)", i, AsString(3 * i));

 

    Sql sql;

    sql.Execute("select * from TEST");

    for(int i = 0; i < sql.GetColumns(); i++)

        Cout() << sql.GetColumnInfo(i).name << '\n';

    while(sql.Fetch())

        Cout() << sql[0] << " \'" << sql[1] << "\'\n";

}

 

As global SQL is regular Sql variable too, it can be used to issue SQL statements.

Warning: While it is possible to issue select statements through SQL, based on experience this is not recommended - way too often result set of select is canceled by issuing some other command, e.g. in routine called as part of Fetch loop. One exception to this rule is using SQL::operator% to fetch single value like String txt = SQL % Select(TEXT).From(DOCTEMPLATE).Where(ID == id); (see further tutorial topics for detailed explanation of this code).

To get information about result set columns, you can use GetColumns to retrieve the number of columns and GetColumnInfo to retrieve information about columns - returns SqlColumnInfo reference with information like name or type of column.

 


3. Using SqlExp

U++ contains an unique feature, "SqlExp". This is a mechanism where you construct SQL statements as C++ expressions (using heavily overloaded operators).

There are three advantages to this approach:

SQL statements are at least partially checked at compile time

As such statements are yet to be interpreted, it is possible to hide some differences between DB engines

It is much easier to create complex dynamic SQL statements

Database entity identifiers (like table or column names) can be defined as SqlId type. For the complete lest of supported SQL statements, see SqlExp in examples.

#include <Core/Core.h>

#include <plugin/sqlite3/Sqlite3.h>

 

using namespace Upp;

 

CONSOLE_APP_MAIN

{

    Sqlite3Session sqlite3;

    if(!sqlite3.Open(ConfigFile("simple.db"))) {

        Cout() << "Can't create or open database file\n";

        return;

    }

    

#ifdef _DEBUG

    sqlite3.SetTrace();

#endif

 

    SQL = sqlite3;

    

    SQL.Execute("drop table TEST");

    SQL.ClearError();

    SQL.Execute("create table TEST (A INTEGER, B TEXT)");

 

    SqlId A("A"), B("B"), TEST("TEST");

 

    for(int i = 0; i < 10; i++)

        SQL * Insert(TEST)(A, i)(B, AsString(3 * i));

 

    Sql sql;

    sql * Select(A, B).From(TEST);

    while(sql.Fetch())

        Cout() << sql[A] << " \'" << sql[B] << "\'\n";

}

 

SqlId identifiers can be also used as parameter of Sql::operator[] to retrieve particular columns of result-set.

 


4. Schema file

Schema files can be used to describe the database schema. Such schema files can be used to upload the schema to the database, to defined SqlId constants and also to work with database records as C++ structures.

Following example demonstrates using schema file to create database schema in SQL database server.

MyApp.sch:

 

TABLE(TEST)

    INT        (A)

    STRING     (B, 200)

END_TABLE

 

MyApp.h

 

 

#ifndef _MyApp_h_

#define _MyApp_h_

 

#include <Core/Core.h>

#include <plugin/sqlite3/Sqlite3.h>

 

using namespace Upp;

 

#define SCHEMADIALECT <plugin/sqlite3/Sqlite3Schema.h>

#define MODEL <Sql04/MyApp.sch>

#include "Sql/sch_header.h"

 

#endif

 

main.cpp

#include "MyApp.h"

 

#include <Sql/sch_schema.h>

#include <Sql/sch_source.h>

 

CONSOLE_APP_MAIN

{

    Sqlite3Session sqlite3;

    if(!sqlite3.Open(ConfigFile("simple.db"))) {

        Cout() << "Can't create or open database file\n";

        return;

    }

    

#ifdef _DEBUG

    sqlite3.SetTrace();

#endif

 

    SQL = sqlite3;

 

    SqlSchema sch(SQLITE3);

    All_Tables(sch);

    SqlPerformScript(sch.Upgrade());

    SqlPerformScript(sch.Attributes());

    SQL.ClearError();

 

    SqlId A("A"), B("B"), TEST("TEST");

 

    for(int i = 0; i < 10; i++)

        SQL * Insert(TEST)(A, i)(B, AsString(3 * i));

 

    Sql sql;

    sql * Select(A, B).From(TEST);

    while(sql.Fetch())

        Cout() << sql[A] << " \'" << sql[B] << "\'\n";

}

 

 


5. Using schema file to define SqlId constants

As names of columns are present in the database schema, it is natural to recycle them to create SqlId constants.

However, due to C++ one definition rule (.sch files are interpreted as C++ sources, using changing set of macros), you have to mark identifiers using underscore:

MyApp.sch:

TABLE_(TEST)

    INT_        (A)

    STRING_     (B, 200)

END_TABLE

 

TABLE_(TEST2)

    INT        (A)

    STRING     (B, 200)

END_TABLE

 

MyApp.h:

#ifndef _MyApp_h_

#define _MyApp_h_

 

#include <Core/Core.h>

#include <plugin/sqlite3/Sqlite3.h>

 

using namespace Upp;

 

#define SCHEMADIALECT <plugin/sqlite3/Sqlite3Schema.h>

#define MODEL <Sql05/MyApp.sch>

#include "Sql/sch_header.h"

 

#endif

 

main.cpp:

 

#include "MyApp.h"

 

#include <Sql/sch_schema.h>

#include <Sql/sch_source.h>

 

CONSOLE_APP_MAIN

{

    Sqlite3Session sqlite3;

    if(!sqlite3.Open(ConfigFile("simple.db"))) {

        Cout() << "Can't create or open database file\n";

        return;

    }

    

#ifdef _DEBUG

    sqlite3.SetTrace();

#endif

 

    SQL = sqlite3;

 

    SqlSchema sch(SQLITE3);

    All_Tables(sch);

    SqlPerformScript(sch.Upgrade());

    SqlPerformScript(sch.Attributes());

    SQL.ClearError();

 

    for(int i = 0; i < 10; i++)

        SQL * Insert(TEST)(A, i)(B, AsString(3 * i));

 

    Sql sql;

    sql * Select(A, B).From(TEST);

    while(sql.Fetch())

        Cout() << sql[A] << " \'" << sql[B] << "\'\n";

}

 

 


6. Using structures defined by schema files

Schema files also define structures that can be used to fetch, insert or update database records. Names of such structures are identical to the names of tables, with S_ prefix:

#include "MyApp.h"

 

#include <Sql/sch_schema.h>

#include <Sql/sch_source.h>

 

CONSOLE_APP_MAIN

{

    Sqlite3Session sqlite3;

    if(!sqlite3.Open(ConfigFile("simple.db"))) {

        Cout() << "Can't create or open database file\n";

        return;

    }

    

#ifdef _DEBUG

    sqlite3.SetTrace();

#endif

 

    SQL = sqlite3;

 

    SqlSchema sch(SQLITE3);

    All_Tables(sch);

    SqlPerformScript(sch.Upgrade());

    SqlPerformScript(sch.Attributes());

    SQL.ClearError();

 

    S_TEST x;

    for(int i = 0; i < 10; i++) {

        x.A = i;

        x.B = AsString(3 * i);

        SQL * Insert(x);

    }

 

    Sql sql;

    sql * Select(x).From(TEST);

    while(sql.Fetch(x))

        Cout() << x.A << " \'" << x.B << "\'\n";

}

 


Recommended tutorials:

If you want to learn more, we have several tutorials that you can find useful:

Skylark - now you know everything about databases - why not to use your knowledge to become web development star?

U++ Core value types - still not very confident with U++. In this tutorial you will learn basics.

Do you want to contribute?