APIs for Connecting to a Database
After the database connection test is successful, the ODBC APIs provide a group of functions to connect to the database, as shown in Table 1.
Function |
API |
---|---|
Allocate a handle. |
SQLAllocHandle is a generic function for allocating a handle. It can replace the following functions:
|
Set environment attributes. |
|
Set connection attributes. |
|
Connect to a database. |
The following uses the development source program DBtest.c as an example (for details about the complete example, see Obtaining and Processing Data in a Database).
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 |
// DBtest.c (compile with: libodbc.so) // For details about program header files and global variables, see the complete example. // Allocate an environment handle. V_OD_erg = SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&V_OD_Env); if ((V_OD_erg != SQL_SUCCESS) && (V_OD_erg != SQL_SUCCESS_WITH_INFO)) { printf("Error AllocHandle\n"); exit(0); } // Set the version information (environment attributes). SQLSetEnvAttr(V_OD_Env, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); // Allocate a connection handle. V_OD_erg = SQLAllocHandle(SQL_HANDLE_DBC, V_OD_Env, &V_OD_hdbc); if ((V_OD_erg != SQL_SUCCESS) && (V_OD_erg != SQL_SUCCESS_WITH_INFO)) { SQLFreeHandle(SQL_HANDLE_ENV, V_OD_Env); exit(0); } // Obtain the username and password. char *userName; userName = getenv("EXAMPLE_USERNAME_ENV"); char *password; password = getenv("EXAMPLE_PASSWORD_ENV"); // Set connection attributes. SQLSetConnectAttr(V_OD_hdbc, SQL_ATTR_AUTOCOMMIT,(SQLPOINTER *)SQL_AUTOCOMMIT_ON, 0); // Connect to the database. userName and password indicate the username and password for connecting to the database respectively. // If the username and password have been set in the odbc.ini file, you can retain "". However, you are advised not to do so because the username and password will be disclosed if the permission for odbc.ini is abused. V_OD_erg = SQLConnect(V_OD_hdbc, (SQLCHAR*) "gaussdb", SQL_NTS, (SQLCHAR*) userName, SQL_NTS, (SQLCHAR*) password, SQL_NTS); if ((V_OD_erg != SQL_SUCCESS) && (V_OD_erg != SQL_SUCCESS_WITH_INFO)) { printf("Error SQLConnect %d\n",V_OD_erg); SQLFreeHandle(SQL_HANDLE_ENV, V_OD_Env); exit(0); } printf("Connected !\n"); |
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot