This topic describes how to build an application using OceanBase Connector/ODBC and OceanBase Cloud to perform basic operations such as creating tables, inserting data, and querying data.
Prerequisites
You have registered an OceanBase Cloud account and created a cluster instance and an OceanBase Cloud tenant in Oracle-compatible mode. For more information, see Create a cluster instance and Create a tenant.
You have installed Visual Studio.
You have installed the OceanBase Connector/ODBC driver.
Note
Download the Windows installation package for the OceanBase ODBC driver from the Drivers and Middleware section on the Resources > Download Center > Enterprise Edition page of the OceanBase official website. The Windows installation package for OceanBase Connector/ODBC is a one-click deployment package; follow the default instructions to install it.
Procedure
Note
The procedure described in this topic is based on using Visual Studio Community 2019 in a Windows environment to compile and run the project. If you are using a different operating system or compiler, the steps may vary slightly.
- Open the
c-oceanbase-odbcproject. - Configure the properties of the
c-oceanbase-odbcproject. - Obtain the connection information for the OceanBase Cloud database.
- Modify the database connection information in the
c-oceanbase-odbcproject. - Build the project.
- Run the application.
- View the output results.
Step 1: Open the c-oceanbase-odbc project
Start Visual Studio Community 2019.
Open an existing project.
On the start page of Visual Studio Community 2019, click Open Project or Solution (P) below Get Started. Alternatively, on the start page, click Continue without code (W) below Get Started; then select File from the top menu bar, then Open, and then Project/Solution (P).
Navigate to the folder containing the c-oceanbase-odbc project, select the project file (
c-oceanbase-odbc.slnorc-oceanbase-odbc.vcxproj), and click Open.
Step 2: Configure the properties of the c-oceanbase-odbc project
Open the project's property page.
Right-click the selected project in Solution Explorer, then select Attribute from the context menu. Alternatively, select Project > Attribute from the top menu bar of Visual Studio, or use the shortcut key Alt + Enter.
Configure the manager settings.
On the property page, find the Configuration (C) drop-down menu at the top. In the drop-down menu, select Debug.
On the property page, find the Platform (P) drop-down menu at the top. In the drop-down menu, select x64.
Configure the character set.
On the property page, select the Advanced tab, and locate the Character Set field. In the drop-down menu, select Use multibyte character set.
Step 3: Obtain the connection information for the OceanBase Cloud database
Log in to the OceanBase Cloud console. On the instance list page, expand the target instance's information, and under the target tenant, select Connect > Get connection string.
For more detailed operations, see Get connection string.
Fill in the corresponding information in the URL below based on your created OceanBase Cloud database.
Example:
obclient -h t********.********.oceanbase.cloud -P 1521 -u oracle001 -p******Parameter description:
-h: The connection address of the OceanBase Cloud database, for example,t********.********.oceanbase.cloud.-P: The port for connecting to the OceanBase Cloud database. Default value: 1521.-u: The account used to access the database.-p: The password of the account.
For more information about the connection string, see Connect to an OceanBase tenant by using OBClient.
Step 4: Modify the database connection information in the c-oceanbase-odbc project
Modify the database connection information in the test_tbl1.cpp file based on the information obtained in Step 3: Obtain the connection information of the OceanBase Cloud database.
Example:
char* mydriver = (char*)"Driver={OceanBase ODBC 2.0 Driver};Server=t********.********.oceanbase.cloud;Port=1521;Database=sys;User=oracle001;Password=******;Option=3;";
Step 5: Build the project
Select the Build menu and then select Build Solution. The compiler output and any error or warning messages are displayed during the build process.
Step 6: Run the application
Select the Debug menu and then select Start Debugging or Run Without Debugging to run the application.
Step 7: View the output results
The output results are displayed in the debug console. You can determine how to process the output based on the program's design logic and code.
Sample project overview
Click c-oceanbase-odbc to download the project code, which is a compressed file named c-oceanbase-odbc.zip.
After decompressing it, you will get a folder named c-oceanbase-odbc. The directory structure is as follows:
c-oceanbase-odbc
├─ c-oceanbase-odbc.sln
├─ c-oceanbase-odbc.vcxproj
├─ c-oceanbase-odbc.vcxproj.filters
├─ c-oceanbase-odbc.vcxproj.user
└─ test_tbl1.cpp
File description:
c-oceanbase-odbc.sln: A solution file for Visual Studio, used to manage one or more projects.c-oceanbase-odbc.vcxproj: A project file for Visual Studio, used to describe the structure and configuration of a C/C++ project.c-oceanbase-odbc.vcxproj.filters: A project filter file for Visual Studio, used to define the directory structure and organization of files in the project.c-oceanbase-odbc.vcxproj.user: A file used to store user-specific project settings.test_tbl1.cpp: A source code file that defines the structure of a data table and implements data table operations.
Introduction to the code in the test_tbl1.cpp file
The test_tbl1.cpp file defines a data table named test_tbl1 and implements operations such as creating the data table, inserting data into it, and querying data from it.
The code in the test_tbl1.cpp file mainly consists of the following parts:
Include header files.
Include the header files
stdio.h,assert.h,windows.h,sql.h, andsqlext.h.Code:
#include <stdio.h> #include <assert.h> #include <windows.h> #include <sql.h> #include <sqlext.h>Define the
odbc_print_errorfunction.This function is used to print error messages when ODBC-related errors occur during program execution. The specific steps are as follows:
- Define the function name
odbc_print_errorand specify the parametersSQLSMALLINT HandleTypeandSQLHANDLE Handleto identify the handle type and handle corresponding to the error message. - Define variables to store error information obtained from ODBC. The types and names of these variables are defined in the ODBC API.
- Use
SQLGetDiagRec()to retrieve the most recent error message generated by ODBC. After this function is called, theSQLState,NativeError, andSQLMessagearrays store the relevant content of the error message. - Use the
fprintffunction to print the error message to the standard output stream. The format string is[%s] (%d) %s\n, which is similar to that of theprintffunction.%sis used for string data,%dfor integer data, and\nindicates a line break.SQLState,NativeError, andSQLMessagecorrespond to the three parameters in the format string, representing the content of the error message to be printed.
Code:
static void odbc_print_error(SQLSMALLINT HandleType, SQLHANDLE Handle) { SQLCHAR SQLState[6]; SQLINTEGER NativeError; SQLCHAR SQLMessage[SQL_MAX_MESSAGE_LENGTH] = { 0 }; SQLSMALLINT TextLengthPtr; SQLGetDiagRec(HandleType, Handle, 1, SQLState, &NativeError, SQLMessage, SQL_MAX_MESSAGE_LENGTH, &TextLengthPtr); fprintf(stdout, "[%s] (%d) %s\n", SQLState, NativeError, SQLMessage); }- Define the function name
Define the
ASSERT_CHECKfunction.This function checks and handles the return values of ODBC function calls, specifically verifying whether an error occurred in the return value of an ODBC API function. If an error is detected, it prints an error message and exits the program. The specific steps are as follows:
- Define the function
ASSERT_CHECKand specify the parametersSQLSMALLINT HandleType,SQLHANDLE Handle, andSQLRETURN rcode, representing the ODBC handle type, ODBC handle, and the return value of the ODBC API function call, respectively. - Use an
ifstatement to check the return value of the ODBC API function. If the return value is notSQL_SUCCESSorSQL_SUCCESS_WITH_INFO, an error occurred in the function call. - Call the
odbc_print_errorfunction to print the ODBC error message. - Call the
assertfunction to perform an assertion check during program execution. If an error occurs in an ODBC function call, the program will be interrupted.
Code:
static void ASSERT_CHECK(SQLSMALLINT HandleType, SQLHANDLE Handle, SQLRETURN rcode) { if (rcode != SQL_SUCCESS && rcode != SQL_SUCCESS_WITH_INFO) { odbc_print_error(HandleType, Handle); assert(0); } }- Define the function
Define the
mainfunction.Define the program's entry function
main, which returns an integer value. In themainfunction, write code related to database connection and data manipulation.Code:
int main() { // Allocate an environment handle // Set the ODBC version environment attribute. // Allocate connection handle // Connect to data source // Create a table // Insert data // Query data // Clean up and release specific resource handles }Define variables.
Define the variable
henv, which is an object of the ODBC environment handle type, used to manage ODBC connections and resource allocation.OutConnStrandOutConnStrLenare used to store the connection string and its length, respectively. These parameters are passed to theSQLDriverConnectfunction when connecting to the database to obtain the return value upon successful connection and some other connection information.Code:
HENV henv; SQLCHAR OutConnStr[255]; SQLSMALLINT OutConnStrLen;Allocate an environment handle.
Use the
SQLAllocHandlefunction to allocate an ODBC environment handle, and use theASSERT_CHECKfunction to check the result of the handle allocation to ensure success. The specific steps are as follows:After the
SQLAllocHandlefunction is executed, it returns a value of typeSQLRETURNindicating the execution result. In the code, this return value is stored in thercodevariable. The parameters of theSQLAllocHandlefunction are as follows:SQL_HANDLE_ENV: Specifies the type of handle to allocate. Here, it isSQL_HANDLE_ENV, indicating that an environment handle is to be allocated.SQL_NULL_HANDLE: Specifies the parent handle. Here, it isSQL_NULL_HANDLE, indicating no parent handle.&henv: A pointer to the variable that stores the allocated handle. Here, it ishenv, the variable for the environment handle.
The
ASSERT_CHECKfunction is used to check the return valuercodefrom theSQLAllocHandlefunction. Ifrcodeis notSQL_SUCCESSorSQL_SUCCESS_WITH_INFO, meaning the handle allocation failed, theASSERT_CHECKfunction will call theodbc_print_errorfunction to print an error message and terminate program execution using theassertmacro.
Code:
SQLRETURN rcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv); ASSERT_CHECK(SQL_HANDLE_ENV, henv, rcode);Set the ODBC version environment attribute.
Use the
SQLSetEnvAttrfunction to set properties of the ODBC environment. It can set some environment-level attributes to affect database connections and driver behavior. Use theASSERT_CHECKfunction to check the result of setting the attribute to ensure success. The specific steps are as follows:After the
SQLSetEnvAttrfunction is executed, it returns a value of typeSQLRETURNindicating the execution result. In the code, this return value is stored in thercodevariable. The parameters of theSQLSetEnvAttrfunction are as follows:henv: The ODBC environment handle, specifying the environment object for which the attribute is to be set.SQL_ATTR_ODBC_VERSION: Specifies the type of environment attribute to set. Here, it isSQL_ATTR_ODBC_VERSION, indicating that the ODBC version attribute is to be set.(void*)SQL_OV_ODBC3: A pointer to the attribute value. Here, it isSQL_OV_ODBC3, indicating that the ODBC version is to be set to ODBC 3.x.0: The length of the attribute value. Here, since the attribute value is an enumeration constant, the length is0.
The
ASSERT_CHECKfunction is used to check the return valuercodefrom theSQLSetEnvAttrfunction. Ifrcodeis notSQL_SUCCESSorSQL_SUCCESS_WITH_INFO, meaning the attribute setting failed, theASSERT_CHECKfunction will call theodbc_print_errorfunction to print an error message and terminate program execution using theassertmacro.
Code:
rcode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); ASSERT_CHECK(SQL_HANDLE_ENV, henv, rcode);Allocate a connection handle.
Use the
SQLAllocHandlefunction to allocate anODBCconnection handle, and use theASSERT_CHECKfunction to check the result of the handle allocation to ensure success. The specific steps are as follows:After the
SQLAllocHandlefunction is executed, it returns a value of typeSQLRETURNindicating the execution result. In the code, this return value is stored in thercodevariable. The parameters of theSQLAllocHandlefunction are as follows:SQL_HANDLE_DBC: Specifies the type of handle to allocate. Here, it isSQL_HANDLE_DBC, indicating that a connection handle is to be allocated.henv: An allocated ODBC environment handle, serving as the parent handle, to associate with the connection handle.&hdbc: A pointer to the variable that stores the allocated connection handle.
The
ASSERT_CHECKfunction is used to check the return valuercodefrom theSQLAllocHandlefunction. Ifrcodeis notSQL_SUCCESSorSQL_SUCCESS_WITH_INFO, meaning the handle allocation failed, theASSERT_CHECKfunction will call theodbc_print_errorfunction to print an error message and terminate program execution using theassertmacro.
Sample code:
SQLHDBC hdbc; rcode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc); ASSERT_CHECK(SQL_HANDLE_DBC, hdbc, rcode);Connect to the data source.
Use the
SQLDriverConnectfunction to connect to the specified ODBC data source, and use theASSERT_CHECKfunction to check the result of the connection operation to ensure a successful connection. The specific steps are as follows:Define a connection string
mydriverthat describes the details required to connect to the database. This string contains the following parts:Driver={OceanBase ODBC 2.0 Driver}: Specifies to use the OceanBase ODBC 2.0 Driver.Server=your_ip: Specifies the connection address of the database.Port=your_port: Specifies the port number to use when connecting to the database.Database=your_schema: Specifies the name of the database to connect to.User=your_use: Specifies the username to use when connecting to the database.Password=your_password: Specifies the password to use when connecting to the database.Option=3: Specifies the connection option. Its value is3, indicating to use a TCP/IP connection.
Use the
SQLDriverConnectfunction to connect to the specified ODBC data source. After the function is executed, it returns an SQLRETURN value indicating the execution result. In the code, this return value is stored in thercodevariable. The function's parameters are as follows:hdbc: The ODBC connection handle, used to establish a connection with the data source.NULL: A reserved parameter that is not used.mydriver: The connection string, which contains all the information required to connect to the database, such as the driver name, database address, port number, database name, username, and password.strlen((char*)mydriver) + 1: The length of the connection string.OutConnStr: An SQLCHAR-type buffer for storing the connection string.255: The length of the buffer.&OutConnStrLen: A pointer to a variable that stores the actual length of the connection string.SQL_DRIVER_NOPROMPT: A connection flag that indicates not to display any prompt dialog boxes during connection.
The
ASSERT_CHECKfunction is used to check the return valuercodeof theSQLDriverConnectfunction. Ifrcodeis notSQL_SUCCESSorSQL_SUCCESS_WITH_INFO, indicating a connection failure, theASSERT_CHECKfunction calls theodbc_print_errorfunction to print an error message and terminates program execution using theassertmacro.
Code:
char* mydriver = (char*)"Driver={OceanBase ODBC 2.0 Driver};Server=your_ip;Port=your_port;Database=your_schema;User=your_use;Password=your_password;Option=3;"; rcode = SQLDriverConnect(hdbc, NULL, (SQLCHAR*)mydriver, strlen((char*)mydriver) + 1, OutConnStr, 255, &OutConnStrLen, SQL_DRIVER_NOPROMPT); ASSERT_CHECK(SQL_HANDLE_DBC, hdbc, rcode);Parameter description for connecting to OceanBase Cloud:
your_ip: Obtained from the-hparameter in the connection string, which is the connection address of OceanBase Cloud.your_port: Obtained from the-Pparameter in the connection string, which is the connection port of OceanBase Cloud.your_schema: The name of the schema to be accessed.your_user: Obtained from the-uparameter in the connection string, which is the account name.your_password: Obtained from the-pparameter in the connection string, which is the account password.
Create a table.
Allocate an ODBC statement handle using the
SQLAllocHandlefunction, then use theSQLExecDirectfunction to execute an SQL statement that creates a table. The code also uses theASSERT_CHECKfunction to check the results of handle allocation and statement execution to ensure the operation succeeds. Finally, release the statement handle using theSQLFreeHandlefunction to free up resources. The specific steps are as follows:Declare an ODBC statement handle
stmt.Allocate an ODBC statement handle using the
SQLAllocHandlefunction.Use the
ASSERT_CHECKfunction to check the return valuercodeof theSQLAllocHandlefunction to ensure the handle was allocated successfully.Execute an SQL statement using the
SQLExecDirectfunction. Here, it executes aCREATE TABLEstatement to create a table namedtest_tbl1.Use the
ASSERT_CHECKfunction to check the return valuercodeof theSQLExecDirectfunction to ensure the statement was executed successfully.Release the
ODBCstatement handle using theSQLFreeHandlefunction.
Code:
SQLHSTMT stmt; rcode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &stmt); ASSERT_CHECK(SQL_HANDLE_STMT, stmt, rcode); rcode = SQLExecDirect(stmt, (SQLCHAR*)"CREATE TABLE test_tbl1(id NUMBER PRIMARY KEY, name VARCHAR2(50),age NUMBER NOT NULL)", SQL_NTS); ASSERT_CHECK(SQL_HANDLE_STMT, stmt, rcode); SQLFreeHandle(SQL_HANDLE_STMT, stmt);Insert data.
Allocate an ODBC statement handle using the
SQLAllocHandlefunction, then use theSQLExecDirectfunction to execute an SQL statement that inserts data into a database table. The code also uses theASSERT_CHECKfunction to check the results of handle allocation and statement execution to ensure the operation succeeds. Finally, release the statement handle using theSQLFreeHandlefunction to free up resources. The specific steps are as follows:Allocate an ODBC statement handle using the
SQLAllocHandlefunction.Use the
ASSERT_CHECKfunction to check the return valuercodeof theSQLAllocHandlefunction to ensure the handle was allocated successfully.Execute an SQL statement using the
SQLExecDirectfunction. Here, it executes anINSERT INTOstatement to insert three records into thetest_tbl1table.Use the
ASSERT_CHECKfunction to check the return valuercodeof theSQLExecDirectfunction to ensure the statement was executed successfully.Release the ODBC statement handle using the
SQLFreeHandlefunction.
Code:
rcode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &stmt); ASSERT_CHECK(SQL_HANDLE_STMT, stmt, rcode); rcode = SQLExecDirect(stmt, (SQLCHAR*)"INSERT INTO test_tbl1 (id,name,age) VALUES (1,'Tom', 18),(2,'Jerry', 20),(3,'Bob', 22)", SQL_NTS); ASSERT_CHECK(SQL_HANDLE_STMT, stmt, rcode); SQLFreeHandle(SQL_HANDLE_STMT, stmt);Query data.
Allocate an ODBC statement handle using the
SQLAllocHandlefunction, then use theSQLExecDirectfunction to execute an SQL statement to retrieve a result set. Next, use theSQLBindColfunction to bind columns from the result set to variables, then use theSQLFetchfunction to fetch rows from the result set one at a time. In awhileloop, print the data from the result set based on the value ofrcode. Finally, release the statement handle using theSQLFreeHandlefunction to free up resources. The specific steps are as follows:Use the
SQLAllocHandlefunction to allocate an ODBC statement handle.Use the
ASSERT_CHECKfunction to check the return valuercodeof theSQLAllocHandlefunction to ensure the handle is allocated successfully.Use the
SQLExecDirectfunction to execute an SQL statement. Here, it executes aSELECTstatement to retrieve all rows from thetest_tbl1table.Use the
ASSERT_CHECKfunction to check the return valuercodeof theSQLExecDirectfunction to ensure the statement is executed successfully.Declare a variable
resof typeSQLLENto store the result of the column binding operation.Declare two variables
idandageof typeSQLINTEGERto store the values of the corresponding columns in the result set.Declare an array
nameof typeSQLCHARto store the values of the corresponding columns in the result set.Use the
SQLBindColfunction to bind the first column of the result set to the variableid.Use the
SQLBindColfunction to bind the second column of the result set to the arrayname.Use the
SQLBindColfunction to bind the third column of the result set to the variableage.Use the
SQLFetchfunction to fetch rows from the result set and store the data in the rows into the bound variables. Thewhileloop continues until all rows have been fetched.In the
whileloop, print the data of the corresponding row based on the value ofrcode. IfrcodeisSQL_ERROR, print an error message.Use the
SQLFreeHandlefunction to release the ODBC statement handle.
Code:
rcode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &stmt); ASSERT_CHECK(SQL_HANDLE_STMT, stmt, rcode); rcode = SQLExecDirect(stmt, (SQLCHAR*)"SELECT * FROM test_tbl1", SQL_NTS); ASSERT_CHECK(SQL_HANDLE_STMT, stmt, rcode); SQLLEN res = SQL_NTS; SQLINTEGER id, age; SQLCHAR name[255]; SQLBindCol(stmt, 1, SQL_C_SLONG, &id, sizeof(id), &res); SQLBindCol(stmt, 2, SQL_C_CHAR, name, sizeof(name), &res); SQLBindCol(stmt, 3, SQL_C_SLONG, &age, sizeof(age), &res); while ((rcode = SQLFetch(stmt)) != SQL_NO_DATA_FOUND) { if (rcode == SQL_ERROR) { printf("sql error!\n"); } else { printf("id:%d, name:%s, age:%ld\n", id, name, age); } } SQLFreeHandle(SQL_HANDLE_STMT, stmt);Perform cleanup and release specific resource handles.
Disconnect from the database and release the related ODBC and environment handles to free up resources. By calling the SQLDisconnect function and the SQLFreeHandle function, the program can properly close the connection to the database and release the related handles. Finally, return 0 to indicate successful program execution. The specific steps are as follows:
Use the SQLDisconnect function to disconnect from the database.
Use the SQLFreeHandle function to release the database connection handle.
Use the SQLFreeHandle function to release the ODBC environment handle.
Return 0 to indicate successful program execution.
Code:
SQLDisconnect(hdbc); SQLFreeHandle(SQL_HANDLE_DBC, hdbc); SQLFreeHandle(SQL_HANDLE_ENV, henv); return 0;
Complete sample code
#include <stdio.h>
#include <assert.h>
#include <windows.h>
#include <sql.h>
#include <sqlext.h>
static void odbc_print_error(SQLSMALLINT HandleType, SQLHANDLE Handle)
{
SQLCHAR SQLState[6];
SQLINTEGER NativeError;
SQLCHAR SQLMessage[SQL_MAX_MESSAGE_LENGTH] = { 0 };
SQLSMALLINT TextLengthPtr;
SQLGetDiagRec(HandleType, Handle, 1, SQLState, &NativeError, SQLMessage, SQL_MAX_MESSAGE_LENGTH, &TextLengthPtr);
fprintf(stdout, "[%s] (%d) %s\n", SQLState, NativeError, SQLMessage);
}
static void ASSERT_CHECK(SQLSMALLINT HandleType, SQLHANDLE Handle, SQLRETURN rcode)
{
if (rcode != SQL_SUCCESS && rcode != SQL_SUCCESS_WITH_INFO) {
odbc_print_error(HandleType, Handle);
assert(0);
}
}
int main()
{
HENV henv;
SQLCHAR OutConnStr[255];
SQLSMALLINT OutConnStrLen;
SQLRETURN rcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
ASSERT_CHECK(SQL_HANDLE_ENV, henv, rcode);
rcode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);
ASSERT_CHECK(SQL_HANDLE_ENV, henv, rcode);
SQLHDBC hdbc;
rcode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
ASSERT_CHECK(SQL_HANDLE_DBC, hdbc, rcode);
char* mydriver = (char*)"Driver={OceanBase ODBC 2.0 Driver};Server=your_ip;Port=your_port;Database=your_schema;User=your_use;Password=your_password;Option=3;";
rcode = SQLDriverConnect(hdbc, NULL, (SQLCHAR*)mydriver, strlen((char*)mydriver) + 1, OutConnStr, 255, &OutConnStrLen, SQL_DRIVER_NOPROMPT);
ASSERT_CHECK(SQL_HANDLE_DBC, hdbc, rcode);
SQLHSTMT stmt;
rcode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &stmt);
ASSERT_CHECK(SQL_HANDLE_STMT, stmt, rcode);
rcode = SQLExecDirect(stmt, (SQLCHAR*)"CREATE TABLE test_tbl1(id NUMBER PRIMARY KEY, name VARCHAR2(50),age NUMBER NOT NULL)", SQL_NTS);
ASSERT_CHECK(SQL_HANDLE_STMT, stmt, rcode);
SQLFreeHandle(SQL_HANDLE_STMT, stmt);
rcode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &stmt);
ASSERT_CHECK(SQL_HANDLE_STMT, stmt, rcode);
rcode = SQLExecDirect(stmt, (SQLCHAR*)"INSERT INTO test_tbl1 (id,name,age) VALUES (1,'Tom', 18),(2,'Jerry', 20),(3,'Bob', 22)", SQL_NTS);
ASSERT_CHECK(SQL_HANDLE_STMT, stmt, rcode);
SQLFreeHandle(SQL_HANDLE_STMT, stmt);
rcode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &stmt);
ASSERT_CHECK(SQL_HANDLE_STMT, stmt, rcode);
rcode = SQLExecDirect(stmt, (SQLCHAR*)"SELECT * FROM test_tbl1", SQL_NTS);
ASSERT_CHECK(SQL_HANDLE_STMT, stmt, rcode);
SQLLEN res = SQL_NTS;
SQLINTEGER id, age;
SQLCHAR name[255];
SQLBindCol(stmt, 1, SQL_C_SLONG, &id, sizeof(id), &res);
SQLBindCol(stmt, 2, SQL_C_CHAR, name, sizeof(name), &res);
SQLBindCol(stmt, 3, SQL_C_SLONG, &age, sizeof(age), &res);
while ((rcode = SQLFetch(stmt)) != SQL_NO_DATA_FOUND)
{
if (rcode == SQL_ERROR) {
printf("sql error!\n");
}
else {
printf("id:%d, name:%s, age:%ld\n", id, name, age);
}
}
SQLFreeHandle(SQL_HANDLE_STMT, stmt);
SQLDisconnect(hdbc);
SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
SQLFreeHandle(SQL_HANDLE_ENV, henv);
return 0;
}
References
For more information about how to connect to OceanBase Cloud, see Overview of connection methods.
For more information about OceanBase Connector/ODBC, see OceanBase Connector/ODBC.