To execute an SQL command you should do the following:

Step 1.Initialize SQL command text
Step 2.Bind input parameters
Step 3.Execute the command
Step 4.Process output

In this section we are going to consider commands like INSERT, UPDATE and DELETE that do not involve fetching data. To execute a SELECT command or a result set generating stored procedures see Fetch result set(s) and Call stored procedure tutorials.

In the following example we assume that the table EMPLOYEES(NAME CHAR(25), AGE INTEGER) exists in the database our connection object is connected to.

Initialize SQL Command Text

To execute a command we need two objects: SAConnection (connection object) and SACommand (command object):

SACommand insert(
    &con,
     "INSERT INTO EMPLOYEES (NAME, AGE) VALUES (:1, :2)");

The code above creates a command object insert based on previously created and connected connection object con (for initializing con object see Connect to database). Second parameter is the command text we want to execute. The command text can also be provided using SACommand::setCommandText method:

SACommand insert(&con);
insert.setCommandText("INSERT INTO EMPLOYEES (NAME, AGE) VALUES (:1, :2)");

Bind Input Parameters

Binding some values to the command is like filling in the gaps in the SQL command statement (marked by :1, :2, :3, ...) with actual data values. The data values can be constants or program variables of appropriate types. To associate a command object with these bind variables you can use the SACommand::operator << as shown below:

insert << "Tom Patt" << 30L;

The order that you associate the values is important (i.e. the first << associates a bind with :1 , the second << with :2).

Another way to bind input variables is directly assigning a value with SAParam object which represents a command parameter. To get appropriated parameter object by its position in SQL statement use SACommand::Param method:

insert.Param(1).setAsString() = "Tom Patt";
insert.Param(2).setAsLong() = 30L;

For more details about binding input variables see in Bind input parameters section.

Execute the Command

Finally we execute the command, which results in the string being inserted into column NAME, and the number being inserted into column AGE:

insert.Execute();

If you want to see the number of rows affected by the command execution use SACommand::RowsAffected method:

int nRows = insert.RowsAffected();

If you want to insert another row of new data, you just have to associate the new bind values with the object and repeat the bind/execute part again:

insert << "Nick Barry" << 35L;
insert.Execute();

Process Output

Processing output parameters and result set is not actual for INSERT, UPDATE and DELETE commands, that's why we discuss this questions in other tutorials:

Need Help?
Send an e-mail to support@sqlapi.com if you want to ask code-level questions, if you’re stuck with a specific error or need advise on the library best practices.