Getting Started with SQLAPI++ Your Hello World App

Welcome to SQLAPI++!

This tutorial introduces you to the essentials of SQLAPI++ by walking you through building a small application that makes a connection to database, inserts some data into a table, and fetches the data back.

Use side navigation for more in-depth explanations of different concepts and techniques, as well as for additional topics not covered by the tutorial.
Basic Application Template
#include <stdio.h>  // for printf
#include <SQLAPI.h> // main SQLAPI++ header

int main(int argc, char* argv[]) {
    SAConnection con;
    
    try {
        con.Connect("my_db", "my_user", "my_password", SA_Oracle_Client);
        printf("We are connected!\n");

        /*
        The rest of the tutorial goes here!
        */
        
        con.Disconnect();
        printf("We are disconnected!\n");
    }
    catch(SAException &x) {
        con.Rollback();
        printf("%s\n", (const char*)x.ErrText());
    }
    
    return 0;
}

This outline for the program demonstrates the following:

  • Include SQLAPI.h to get access to the library
  • To connect to database, allocate a SAConnection object and use SAConnection::Connect method to connect to your database provider using your credentials
  • Handle SAException exception for all database related problems including connectivity, database client and database server errors
  • You can optionally use SAConnection::Disconnect to disconnect from the server. If you don't, the library will implicitly do that for you when connection object is destructed
Inserting data into a table
SACommand insert(&con, "insert into employees (name, age) values (:1, :2)");

insert << "Tom Patt" << 30;
insert.Execute();
insert << "Nick Barry" << 35;
insert.Execute();

This snippet of code demonstrates the following:

  • To execute any SQL command on the server you create a SACommand object, passing it a valid connection object
  • SQLAPI++ supports parameter markers to bind input data to SQL commands. This example uses positional parameters, but the library also supports named parameters
  • To actually send the command to the server use SACommand::Execute method
Reading data from a table
SACommand select(&con, "select name, age from employees where age > :1");

select << 30;
select.Execute();

while(select.FetchNext()) {
    SAString sName = select[1];
    long nAge = select[2];
    printf("Name: %s, age: %d \n", sName, nAge);
}

In this code snippet:

  • You use SACommand again, this time for SELECT statement
  • You use parameter binding, just like we did for INSERT command
  • Use SACommand::Execute to send your query to the server
  • SACommand::FetchNext method is used to fetch results set row by row
  • You access SELECT fields in the result set using field access operators. This example uses positional operators but the library also supports access by name
This is it - you just mastered all the basics!
Next Steps