powered by simpleCommunicator - 2.0.59     © 2025 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / C++ [игнор отключен] [закрыт для гостей] / Подключиться к Oracle из C++
11 сообщений из 11, страница 1 из 1
Подключиться к Oracle из C++
    #38804242
sitev_ru
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Необходимо подключиться к Oracle из C++. Покажите, плиз, работающий пример?
...
Рейтинг: 0 / 0
Подключиться к Oracle из C++
    #38804318
Фотография mayton
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Ищи по ключевому слову OCI (Oracle Call Interface). Материалов - валом.
...
Рейтинг: 0 / 0
Подключиться к Oracle из C++
    #38804334
sitev_ru
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
mayton,

Я поэтому и пишу "подскажите РАБОТАЮЩИЙ пример", потому что толком не нашёл работающего (хотя может я плохо разбираюсь в сборке готовых проектов)...

Перепробывал несколько примеров и везде столкнулся с проблемой компиляции. Например, вот этот:

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
#include <stdio.h>
#include <string.h>
#include <oci.h>

void checkerr(OCIError* err, sword status) {
    text errbuf[512];
    ub4 buflen;
    sb4 errcode;

    switch (status) {
    case OCI_SUCCESS:
        break;
    case OCI_SUCCESS_WITH_INFO:
        printf("Error - OCI_SUCCESS_WITH_INFO\n");
        break;
    case OCI_NEED_DATA:
        printf("Error - OCI_NEED_DATA\n");
        break;
    case OCI_NO_DATA:
        printf("Error - OCI_NO_DATA\n");
        break;
    case OCI_ERROR:
        OCIErrorGet(err, (ub4)1, (text *)NULL, &errcode,
            errbuf, (ub4) sizeof(errbuf), (ub4)OCI_HTYPE_ERROR);
        printf("Error - %s\n", errbuf);
        break;
    case OCI_INVALID_HANDLE:
        printf("Error - OCI_INVALID_HANDLE\n");
        break;
    case OCI_STILL_EXECUTING:
        printf("Error - OCI_STILL_EXECUTE\n");
        break;
    case OCI_CONTINUE:
        printf("Error - OCI_CONTINUE\n");
        break;
    default:
        break;
    }
}


void parse_connect_string(
    char* connect_str,  /* in   */
    text  username[30], /* out  */
    text  password[30], /* out  */
    text  dbname[30]  /* out  */
    ) {

    username[0] = 0;
    password[0] = 0;
    dbname[0] = 0;

    char* to = (char*)username;

    while (*connect_str) {
        if (*connect_str == '/') {
            *to = 0;
            to = (char*)password;
            connect_str++;
            continue;
        }
        if (*connect_str == '@') {
            *to = 0;
            to = (char*)dbname;
            connect_str++;
            continue;
        }
        *to = *connect_str;
        to++;
        connect_str++;
    }
    *to = 0;
}

int main(int argc, char* argv[]) {
    /*  (void) OCIInitialize((ub4) OCI_DEFAULT, (dvoid *)           0,
    (dvoid * (*)(dvoid *, size_t))         0,
    (dvoid * (*)(dvoid *, dvoid *, size_t))0,
    (void (*)(dvoid *, dvoid *))           0 ); */



    /* The environment handle defines a context in which all OCI functions are
    invoked. Each environment handle contains a memory cache, which allows for
    fast memory access. All memory allocation under the environment handle is
    done from this cache. Access to the cache is serialized if multiple
    threads try to allocate memory under the same environment handle. When
    multiple threads share a single environment handle, they may block on
    access to the cache. The environment handle is passed as the parent
    parameter to the OCIHandleAlloc() call to allocate all other handle types.
    Bind and define handles are allocated implicitly.
    */
    OCIEnv*       env;

    /* The error handle is passed as a parameter to most OCI calls. The error
    handle maintains information about errors that occur during an OCI
    operation. If an error occurs in a call, the error handle can be passed to
    OCIErrorGet() to obtain additional information about the error that
    occurred. Allocating the error handle is one of the first steps in an OCI
    application because most OCI calls require an error handle as one of its
    parameters. */
    OCIError*     err;

    OCIServer*    srv;
    OCISvcCtx*    svc;
    OCISession*   ses;

    text          username[30];
    text          password[30];
    text          dbname[30];

    sword         r;

    if (argc < 2) {
        printf("usage %s username/password[@dbname]\n");
        return -1;
    }

    parse_connect_string(argv[1], username, password, dbname);

    env = 0;
    err = 0;
    srv = 0;
    svc = 0;
    ses = 0;

    int len = 0;

    r = OCIEnvCreate(&env, OCI_DEFAULT, 0, 0, 0, 0, 0, 0);

    if (r != OCI_SUCCESS)  {
        printf("OCIEnvCreate failed!\n");
        goto clean_up;
    }

    OCIHandleAlloc(env, (dvoid**)&err, OCI_HTYPE_ERROR, 0, 0);
    OCIHandleAlloc(env, (dvoid**)&srv, OCI_HTYPE_SERVER, 0, 0);
    OCIHandleAlloc(env, (dvoid**)&svc, OCI_HTYPE_SVCCTX, 0, 0);
    OCIHandleAlloc(env, (dvoid**)&ses, OCI_HTYPE_SESSION, 0, 0);

    len = strlen((char*)dbname);
    r = OCIServerAttach(srv, err, dbname, len, (ub4)OCI_DEFAULT);
    if (r != OCI_SUCCESS) {
        checkerr(err, r);
        goto clean_up;
    }

    /* set attribute server context in the service context */
    OCIAttrSet(svc, OCI_HTYPE_SVCCTX, srv, 0, OCI_ATTR_SERVER, err);

    OCIAttrSet(ses, OCI_HTYPE_SESSION, username, strlen((char*)username), OCI_ATTR_USERNAME, err);
    OCIAttrSet(ses, OCI_HTYPE_SESSION, password, strlen((char*)password), OCI_ATTR_PASSWORD, err);

    r = OCISessionBegin(svc, err, ses, OCI_CRED_RDBMS, OCI_DEFAULT);
    checkerr(err, r);


clean_up:

    if (env) OCIHandleFree(env, OCI_HTYPE_ENV);
    if (err) OCIHandleFree(err, OCI_HTYPE_ERROR);
    if (srv) OCIHandleFree(srv, OCI_HTYPE_SERVER);
    if (svc) OCIHandleFree(svc, OCI_HTYPE_SVCCTX);

    OCITerminate(OCI_DEFAULT);

    return 0;
}



Выдаёт ошибки:
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
Description Resource    Path    Location    Type
make: *** [oci6linux] Error 1   oci6linux           C/C++ Problem
undefined reference to `OCIAttrSet' oci6linux.cpp   /oci6linux/src  line 154    C/C++ Problem
undefined reference to `OCIAttrSet' oci6linux.cpp   /oci6linux/src  line 156    C/C++ Problem
undefined reference to `OCIAttrSet' oci6linux.cpp   /oci6linux/src  line 157    C/C++ Problem
undefined reference to `OCIEnvCreate'   oci6linux.cpp   /oci6linux/src  line 134    C/C++ Problem
undefined reference to `OCIErrorGet'    oci6linux.cpp   /oci6linux/src  line 29 C/C++ Problem
undefined reference to `OCIHandleAlloc' oci6linux.cpp   /oci6linux/src  line 141    C/C++ Problem
undefined reference to `OCIHandleAlloc' oci6linux.cpp   /oci6linux/src  line 142    C/C++ Problem
undefined reference to `OCIHandleAlloc' oci6linux.cpp   /oci6linux/src  line 143    C/C++ Problem
undefined reference to `OCIHandleAlloc' oci6linux.cpp   /oci6linux/src  line 144    C/C++ Problem
undefined reference to `OCIHandleFree'  oci6linux.cpp   /oci6linux/src  line 165    C/C++ Problem
undefined reference to `OCIHandleFree'  oci6linux.cpp   /oci6linux/src  line 166    C/C++ Problem
undefined reference to `OCIHandleFree'  oci6linux.cpp   /oci6linux/src  line 167    C/C++ Problem
undefined reference to `OCIHandleFree'  oci6linux.cpp   /oci6linux/src  line 168    C/C++ Problem
undefined reference to `OCIServerAttach'    oci6linux.cpp   /oci6linux/src  line 147    C/C++ Problem
undefined reference to `OCISessionBegin'    oci6linux.cpp   /oci6linux/src  line 159    C/C++ Problem
undefined reference to `OCITerminate'   oci6linux.cpp   /oci6linux/src  line 170    C/C++ Problem



Что не так?
...
Рейтинг: 0 / 0
Подключиться к Oracle из C++
    #38804349
Basil A. Sidorov
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Oracle Instant Client .
Среди загрузок есть SDK с заголовочными файлами, библиотеками и примерами.
...
Рейтинг: 0 / 0
Подключиться к Oracle из C++
    #38804384
sitev_ru
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Basil A. Sidorov,

загружал, пробывал... давайте ещё раз попробуем вместе??? может не так что-то делаю...

скачал файлики rpm, установил их в линуксе (у меня CentOS)

Пример, лежит здесь: /usr/share/oracle/10.2.0.5/client64
Инслуды здесь: /usr/include/oracle/10.2.0.5/client64
Библиотеки здесь: /usr/lib/oracle/10.2.0.5/client64

Компилю:
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
gcc cdemo81.c -I/usr/include/oracle/10.2.0.5/client64 -L/usr/lib/oracle/10.2.0.5/client64

/tmp/ccqr5hRx.o: In function `main':
cdemo81.c:(.text+0xd7): undefined reference to `OCIEnvCreate'
cdemo81.c:(.text+0x128): undefined reference to `OCIHandleAlloc'
cdemo81.c:(.text+0x151): undefined reference to `OCIHandleAlloc'
cdemo81.c:(.text+0x17a): undefined reference to `OCIHandleAlloc'
cdemo81.c:(.text+0x1a3): undefined reference to `OCIServerAttach'
cdemo81.c:(.text+0x1d3): undefined reference to `OCIAttrSet'
cdemo81.c:(.text+0x1fc): undefined reference to `OCIHandleAlloc'
cdemo81.c:(.text+0x238): undefined reference to `OCIAttrSet'
cdemo81.c:(.text+0x274): undefined reference to `OCIAttrSet'
cdemo81.c:(.text+0x29f): undefined reference to `OCISessionBegin'
cdemo81.c:(.text+0x2e7): undefined reference to `OCIAttrSet'
cdemo81.c:(.text+0x310): undefined reference to `OCIHandleAlloc'
cdemo81.c:(.text+0x351): undefined reference to `OCIHandleAlloc'
cdemo81.c:(.text+0x3a6): undefined reference to `OCIStmtPrepare'
cdemo81.c:(.text+0x41a): undefined reference to `OCIDefineByPos'
cdemo81.c:(.text+0x473): undefined reference to `OCIStmtExecute'
cdemo81.c:(.text+0x505): undefined reference to `OCIHandleAlloc'
cdemo81.c:(.text+0x572): undefined reference to `OCIStmtPrepare'
cdemo81.c:(.text+0x5c7): undefined reference to `OCIStmtPrepare'
cdemo81.c:(.text+0x659): undefined reference to `OCIBindByName'
cdemo81.c:(.text+0x6e6): undefined reference to `OCIBindByName'
cdemo81.c:(.text+0x76f): undefined reference to `OCIBindByName'
cdemo81.c:(.text+0x7f8): undefined reference to `OCIBindByName'
cdemo81.c:(.text+0x881): undefined reference to `OCIBindByName'
cdemo81.c:(.text+0x92e): undefined reference to `OCIBindByPos'
cdemo81.c:(.text+0x9e9): undefined reference to `OCIDefineByPos'
cdemo81.c:(.text+0xc18): undefined reference to `OCIStmtExecute'
cdemo81.c:(.text+0xcd1): undefined reference to `OCIStmtExecute'
cdemo81.c:(.text+0xd6e): undefined reference to `OCIStmtExecute'
cdemo81.c:(.text+0xdea): undefined reference to `OCITransCommit'
/tmp/ccqr5hRx.o: In function `checkerr':
cdemo81.c:(.text+0xf30): undefined reference to `OCIErrorGet'
/tmp/ccqr5hRx.o: In function `cleanup':
cdemo81.c:(.text+0xf9b): undefined reference to `OCIHandleFree'
collect2: ld returned 1 exit status



Как исправить ошибки???
...
Рейтинг: 0 / 0
Подключиться к Oracle из C++
    #38804436
Basil A. Sidorov
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Компоновщику нужны имена файлов, в которых расположена та или иная библиотечная функция.
Только после этого он пробежится по списку каталогов из LIB.
...
Рейтинг: 0 / 0
Подключиться к Oracle из C++
    #38804607
Dimitry Sibiryakov
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
sitev_ruКак исправить ошибки???
Изучить основы работы с кмпилятором С. В частности - стадию линковки. Ещё точнее -
указание библиотек.
Posted via ActualForum NNTP Server 1.5
...
Рейтинг: 0 / 0
Подключиться к Oracle из C++
    #38804645
sitev_ru
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Код: plaintext
1.
gcc cdemo81.c -I/usr/include/oracle/10.2.0.5/client64 -L/usr/lib/oracle/10.2.0.5/client64 -loci



так? почему то не работает...
...
Рейтинг: 0 / 0
Подключиться к Oracle из C++
    #38804717
Фотография mayton
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
sitev_ru
Код: plaintext
1.
gcc cdemo81.c -I/usr/include/oracle/10.2.0.5/client64 -L/usr/lib/oracle/10.2.0.5/client64 -loci



так? почему то не работает...
Когда ты говоришь - не работает - то должен публиковать сообщение об ошибке. Если код или месседж
изменяется то мы видим прогресс в решении проблемы.

Если ты просто горестно сообщаешь о том что "всё пропало" то у нас есть только эмоции.

Можем сочувствовать и также охать.
...
Рейтинг: 0 / 0
Подключиться к Oracle из C++
    #38804732
sitev_ru
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
mayton,

gcc cdemo81.c -I/usr/include/oracle/10.2.0.5/client64 -L/usr/lib/oracle/10.2.0.5/client64 -lociei

Лежит там такой файлик libociei, но всё равно выдаёт:

Код: plaintext
1.
cannot find -lociei
...
Рейтинг: 0 / 0
Подключиться к Oracle из C++
    #38804917
Dimitry Sibiryakov
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Ну та с чего ты решил, что нужно линковать его, а не то, что в документации написано?
Posted via ActualForum NNTP Server 1.5
...
Рейтинг: 0 / 0
11 сообщений из 11, страница 1 из 1
Форумы / C++ [игнор отключен] [закрыт для гостей] / Подключиться к Oracle из C++
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]