-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathodbc.c
More file actions
88 lines (74 loc) · 2.5 KB
/
odbc.c
File metadata and controls
88 lines (74 loc) · 2.5 KB
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
#include <stdlib.h>
#include <stdio.h>
#include <sql.h>
#include <sqlext.h>
#include "odbc.h"
/* REPORT OF THE MOST RECENT ERROR USING HANDLE handle */
void odbc_extract_error(char *fn, SQLHANDLE handle, SQLSMALLINT type) {
SQLINTEGER i = 0;
SQLINTEGER native;
SQLCHAR state[ 7 ];
SQLCHAR text[256];
SQLSMALLINT len;
SQLRETURN ret;
fprintf(stderr, "\nThe driver reported the following diagnostics while running %s\n\n", fn);
do {
ret = SQLGetDiagRec(type, handle, ++i, state, &native, text, sizeof(text), &len );
if (SQL_SUCCEEDED(ret)) {
printf("%s:%d:%d:%s\n", state, i, native, text);
}
} while( ret == SQL_SUCCESS );
}
/* STANDARD CONNECTION PROCEDURE */
int odbc_connect(SQLHENV* env, SQLHDBC* dbc) {
SQLRETURN ret;
/* Allocate an environment handle */
ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, env);
if (!SQL_SUCCEEDED(ret)) {
odbc_extract_error("", *env, SQL_HANDLE_ENV);
return ret;
}
/* We want ODBC 3 support */
ret = SQLSetEnvAttr(*env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
if (!SQL_SUCCEEDED(ret)) {
odbc_extract_error("", *env, SQL_HANDLE_ENV);
return ret;
}
/* Allocate a connection handle */
ret = SQLAllocHandle(SQL_HANDLE_DBC, *env, dbc);
if (!SQL_SUCCEEDED(ret)) {
odbc_extract_error("", *dbc, SQL_HANDLE_DBC);
return ret;
}
/* Connect to the DSN mydsn */
/* You will need to change mydsn to one you have created and tested */
ret = SQLDriverConnect(*dbc, NULL, (SQLCHAR*) "DRIVER=PostgreSQL ANSI;DATABASE=flight;SERVER=localhost;PORT=5432;UID=alumnodb;PWD=alumnodb;", SQL_NTS, NULL, 0, NULL, SQL_DRIVER_COMPLETE);
if (!SQL_SUCCEEDED(ret)) {
odbc_extract_error("", *dbc, SQL_HANDLE_DBC);
return ret;
}
return ret;
}
/* STANDARD DISCONNECTION PROCEDURE */
int odbc_disconnect(SQLHENV env, SQLHDBC dbc) {
SQLRETURN ret;
/* Disconnect from database */
ret = SQLDisconnect(dbc);
if (!SQL_SUCCEEDED(ret)) {
odbc_extract_error("", dbc, SQL_HANDLE_DBC);
return ret;
}
/* Free connection handle */
ret = SQLFreeHandle(SQL_HANDLE_DBC, dbc);
if (!SQL_SUCCEEDED(ret)) {
odbc_extract_error("", dbc, SQL_HANDLE_DBC);
return ret;
}
/* Free environment handle */
ret = SQLFreeHandle(SQL_HANDLE_ENV, env);
if (!SQL_SUCCEEDED(ret)) {
odbc_extract_error("", env, SQL_HANDLE_ENV);
return ret;
}
return ret;
}