1. 程式人生 > 實用技巧 >嵌入式SQL舉例

嵌入式SQL舉例

#include <stdio.h>
#include <string.h>

int prompt(char cid_prompt[], int n, char cust_id[], int m);

exec sql include sqlca;

char cid_prompt[] = "Please enter customer id: ";

int main()
{
    exec sql begin declare section;
        char cust_id[5], cust_name[14];
        float cust_discnt;
        char user_name[20], user_pwd[20];
    exec sql end declare section;

    exec sql whenever sqlerror goto report_error;
    exec sql whenever not found goto notfound;

    strcpy(user_name, "poneilsql");
    strcpy(user_pwd, "XXX");

    exec sql connect :user_name identified by :user_pwd;

    while (prompt(cid_prompt, 1, cust_id, 4) >= 0) {
        exec sql select cname, discnt
            into :cust_name, :cust_discnt
            from customers where cid=:cust_id;
        exec sql commit work;
        printf("Customer's name is %s and discount is %5.1\n", cust_name, cust_discnt);
        continue;

notfound: printf("Can't find customer %s, continuing\n", cust_id);
    }

    exec sql commit release;
    return 0;

report_error:
    printf("error\n");
    exec sql rollback release;
    return 1;
}