Updated on 2024-06-03 GMT+08:00

Executing SQL Statements

  1. Create a table.

    EXEC SQL CREATE TABLE foo (a int, b varchar);

  2. Insert a row.

    EXEC SQL INSERT INTO foo VALUES (5, 'abc');

  3. Delete a row.

    EXEC SQL DELETE FROM foo WHERE a = 5;

  4. Update table data.

    EXEC SQL UPDATE foo SET b = 'gdp' WHERE a = 7;

  5. Query data in a single row.

    EXEC SQL SELECT a INTO :var_a FROM foo WHERE b = 'def';

A complete example is as follows:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int main ()
{
    ECPGdebug (1, stderr);

    EXEC SQL BEGIN DECLARE SECTION;
    int var_a;
    EXEC SQL END DECLARE SECTION;
    /* Create testdb in advance. */
    EXEC SQL CONNECT TO testdb;
    // Create a table.
    EXEC SQL CREATE TABLE foo (a int, b varchar);
        // Insert data.
    EXEC SQL INSERT INTO foo VALUES (5, 'abc');
    EXEC SQL INSERT INTO foo VALUES (6, 'def');
    EXEC SQL INSERT INTO foo VALUES (7, 'ghi');

    // Delete a row.
    EXEC SQL DELETE FROM foo WHERE a = 5;
    // Update table data.
    EXEC SQL UPDATE foo SET b = 'gdp' WHERE a = 7;
    // Query table data in a single row.
    EXEC SQL SELECT a INTO :var_a FROM foo WHERE b = 'def';
    // Print the query results.
    printf("select res is %d\n", var_a);

    EXEC SQL DISCONNECT;

    return 0;
}