Click here to view and discuss this page in DocCommentXchange. In the future, you will be sent there automatically.

SQL Anywhere 10.0.1 » UltraLite - C and C++ Programming » Tutorial: Build an Application Using ODBC

Lesson 3: Connect to the database Next Page

Lesson 4: Insert data into the database


ODBC provides a set of functions to carry out operations on the database. This lesson uses the simplest statement, SQLExecDirect.

Write code to insert data into the database
  1. Add an insert function to sample.cpp:

    static ul_bool insert( SQLHANDLE hcon )
    {
        SQLRETURN retn;
        SQLHANDLE hstmt;
        retn = SQLAllocHandle( SQL_HANDLE_STMT, hcon, &hstmt );
        static const ul_char * sql = UL_TEXT( 
         "INSERT customer( id, fname, lname ) VALUES ( 42, 'jane', 'doe' )" );
        retn = SQLExecDirect( hstmt, (SQLTCHAR*)sql, SQL_NTS );
        if( retn == SQL_SUCCESS ) {
            _tprintf( "success in insert.\n" );
        } else {
            _tprintf( "error in insert: %d.\n", retn );
        retn = SQLFreeHandle( SQL_HANDLE_STMT, hstmt );
        hstmt = 0;
        }
        return retn == SQL_SUCCESS;
    }
  2. Call insert from the main function.

    Alter your main function in sample.cpp so that it reads as follows:

    int main() {
        SQLHANDLE henv;
        SQLHANDLE hcon;
        henv = opendb();
        hcon = connect( henv );
        insert( hcon );
        disconnect( hcon, henv );
        closedb( henv );
        return 0;
    }
  3. Compile, link, and run your application to confirm that the application builds properly.

    You should see that the application reports success on inserting the data.

For more information about the function called in this procedure, see SQLExecDirect function.