This topic describes how to use OceanBase Connector/C and OceanBase Cloud to build an application for basic database operations, such as table creation, data insertion, and data query.
Download the c-oceanbase-capi sample project Prerequisites
- You have registered an OceanBase Cloud account, and created a cluster instance and an Oracle-compatible tenant in OceanBase Cloud. For more information, see Create a cluster instance and Create a tenant.
- You have obtained the connection string of the Oracle-compatible tenant. For more information, see Obtain the connection string.
- You have installed OceanBase Connector/C. Contact OceanBase Technical Support to obtain the installation package of OceanBase Connector/C for Windows.
- You have installed Visual Studio.
Procedure
Note
The steps provided in this topic are for compiling and running the project by using Visual Studio Community 2019 in Windows. If you use another operating system or compiler, the procedure can be slightly different.
Step 1: Open the c-oceanbase-capi project
Start Visual Studio Community 2019.
Open an existing project.
In the start window of Visual Studio Community 2019, click Open a project or solution (P) under Get started. Alternatively, click Continue without code (W) in the lower right corner, and choose File > Open > Project/Solution (P) in the menu bar of the page that appears.
Browse to the c-oceanbase-capi folder, select the project file c-oceanbase-capi.sln or c-oceanbase-capi.vcxproj, and click Open.
Step 2: Configure the properties for the c-oceanbase-capi project
Go to the property page of the project.
Right-click the selected project in Solution Explorer and choose Properties from the menu, choose Project > Properties from the top menu bar, or use the keyboard shortcut Alt + Enter.
Configure manager settings.
On the property page, select Debug from the Configuration drop-down list.
On the property page, select x64 from the Platform drop-down list.
Set the header file path for the compiler.
Click the VC++ Directories tab, find and edit the Include Directories field to add the header file path of the OceanBase Connector/C library.
Set the link library path for the compiler.
Click the VC++ Directories tab, find and edit the Library Directories field to add the link library path of the OceanBase Connector/C library.
Set the character set.
Click the Advanced tab and find the Character Set field. Select Use Multi-Byte Character Set from the drop-down list.
Step 3: Modify the database connection information in the c-oceanbase-capi project
Modify the database connection information in the test_tbl1.cpp file based on the obtained connection string mentioned in the "Prerequisites" section.
Here is an example:
if (NULL == mysql_real_connect(&con_oboracle, "t5******.********.oceanbase.cloud", "test_user", "******", "sys", 3306, NULL, 0))
The parameters are described as follows:
- The endpoint is
t5******.********.oceanbase.cloud. - The access port is
3306. - The name of the database to be accessed is
sys. - The tenant account is
test_user. - The password is
******.
Step 4: Build the project
Choose Build > Build Solution. The output of the compiler and errors or warning messages if any are displayed during the build process.
Step 5: Run the application
Choose Debug > Start Debugging or choose Debug > Start Without Debugging to run the application.
Step 6: Check the output
The output is displayed in the debug console. You can determine how to handle the output based on the design logic and code of the application.
Project code
Click here to download the project code, which is a package named c-oceanbase-capi.zip.
Decompress the package to obtain a folder named c-oceanbase-capi. The directory structure is as follows:
c-oceanbase-capi
├─ c-oceanbase-capi.sln
├─ c-oceanbase-capi.vcxproj
├─ c-oceanbase-capi.vcxproj.filters
├─ c-oceanbase-capi.vcxproj.user
└─ test_tbl1.cpp
The files and directories are described as follows:
c-oceanbase-capi.sln: the solution file in Visual Studio that manages one or more projects.c-oceanbase-capi.vcxproj: the project file in Visual Studio that describes the structure and configuration of a C/C++ project.c-oceanbase-capi.vcxproj.filters: the project filter file in Visual Studio that defines the directory structure and organization of files in the project.c-oceanbase-capi.vcxproj.user: the file that stores user-specific project settings.test_tbl1.cpp: the source code file that defines a data table and implements data table operations.
Code in test_tbl1.cpp
The test_tbl1.cpp file defines and creates a data table named test_tbl1 and implements the operations to insert data into and query data from the table.
Perform the following steps to configure the test_tbl1.cpp file:
Reference header files and library files.
- Reference header files
stdio.h,stdlib.h, andmysql.h. - Specify the specific library files
Shlwapi.lib,ws2_32.lib,Crypt32.lib,Secur32.lib, andobclnt.libto be linked by the linker. These library files are the Windows API library, WinSock library, encryption library, security library, and OceanBase client library.
The sample code is as follows:
#include <stdio.h> #include <stdlib.h> #include <mysql.h> #pragma comment(lib, "Shlwapi.lib") #pragma comment( lib, "ws2_32.lib" ) #pragma comment(lib, "Crypt32.lib") #pragma comment(lib, "Secur32.lib") #pragma comment(lib, "obclnt.lib")- Reference header files
Define the
mainfunction.Define the entry function
mainfor the application and return an integer value. In themainfunction, write the code related to database connections and data operations.The sample code is as follows:
int main() { // Create a connection instance object. // Connect to the database. // Create a table. // Insert data. // Query data. // ... }Declare variables and arrays.
- Declare the
con_oboraclevariable of theMYSQLtype. With this variable, you can create a connection instance. - Declare the character array
sql_strwhose length is1024and initial value is{ 0 }. This array stores SQL statements.
The sample code is as follows:
MYSQL con_oboracle; char sql_str[1024] = { 0 };- Declare the
Initialize the connection object.
Initialize the connection object
con_oboracleand perform follow-up operations based on the initialization result. If the initialization fails, print an error message and return a non-zero value. If the initialization succeeds, print a success message and continue with subsequent operations. Perform the following steps:Call the
mysql_init()function to initialize the connection objectcon_oboracle. The function returns a pointer to the initialized connection object, orNULLif the initialization fails.NULLis a macro that represents a null pointer. TheNULLmacro is compared with the return value of themysql_init()function to determine whether the initialization is successful.Call the
fprintf()function to print an error message to the standard error streamstderr. The first argument to thefprintf()function is the output stream, "Error: %s\n" is the formatted string, andmysql_error(&con_oboracle)is the actual argument that replaces%sin the formatted string.mysql_error(&con_oboracle)is the error message returned for getting thecon_oboracleconnection object.Use
return 1to exit themainfunction and return a non-zero value if initialization fails. This value can be used to indicate the status where the application is abnormally terminated or the initialization fails.
Print a success message when the initialization succeeds. This way, you can check in the console whether the initialization of the connection object is successful.
The sample code is as follows:
if (NULL == mysql_init(&con_oboracle)) { fprintf(stderr, "Error: %s\n", mysql_error(&con_oboracle)); return 1; } printf("mysql_init() success\n");Connect to the database.
Connect to the database from the application, and perform follow-up operations based on the connection result. If the connection fails, print an error message and return a non-zero value. If the connection succeeds, print a success message and continue with subsequent operations. Perform the following steps:
Call the
mysql_real_connect()function to connect to the database. The function returns a pointer to the connected object, orNULLif the connection fails.Call the
fprintf()function to print an error message to the standard error streamstderr. The first argument to thefprintf()function is the output stream, "Error: %s\n" is the formatted string, andmysql_error(&con_oboracle)is the actual argument that replaces%sin the formatted string.mysql_error(&con_oboracle)is the error message returned for getting thecon_oboracleconnection object.Use
return 1to exit themainfunction and return a non-zero value if the connection fails. This value can be used to indicate the status where the program is abnormally terminated or the connection fails.
Print a success message when the connection succeeds. This way, you can check in the console whether the connection to the database is successful.
The sample code is as follows:
if (NULL == mysql_real_connect(&con_oboracle, "your_ip", "your_user", "your_password", "your_schema", your_port, NULL, 0)) { fprintf(stderr, "Error: %s\n", mysql_error(&con_oboracle)); return 1; } printf("mysql_real_connect() success\n");The following parameters are required to connect to OceanBase Cloud:
your_ip: the access address of OceanBase Cloud. The value is sourced from the-hparameter in the connection string.your_user: the account name. The value is sourced from the-uparameter in the connection string.your_password: the account password. The value is sourced from the-pparameter in the connection string.your_schema: the name of the database to be accessed. The value is sourced from the-Dparameter in the connection string.your_port: the access port of OceanBase Cloud. The value is sourced from the-Pparameter in the connection string.
Create a table.
Execute an SQL statement to create a table. Print a success message if the table is created successfully. Print an error message and exit the program if the table creation fails. Perform the following steps:
Call the
sprintf_s()function to format and store an SQL statement in ansql_strarray. This SQL statement creates thetest_tbl1table that contains theid(primary key),name, andagecolumns.Call the
mysql_query()function to execute the SQL statement.&con_oboracleis a pointer to the database connection object on which the SQL statement is executed.sql_stris the SQL statement to execute. Check whether the execution is successful. If the execution fails (with a non-zero return value), the following code block is executed.Call the
fprintf()function to print an error message to the standard error streamstderr. The first argument to thefprintf()function is the output stream, "Error: %s\n" is the formatted string, andmysql_error(&con_oboracle)is the actual argument that replaces%sin the formatted string.mysql_error(&con_oboracle)is the error message returned for getting thecon_oboracleconnection object.Close the connection to the database and release the resources of the connection object.
Use
return 1to exit themainfunction and return the value1if the table creation fails, indicating that the application is abnormally terminated.
Print a success message if the table is created successfully.
The sample code is as follows:
sprintf_s(sql_str, "CREATE TABLE test_tbl1(id NUMBER PRIMARY KEY, name VARCHAR2(50),age NUMBER NOT NULL)"); if (mysql_query(&con_oboracle, sql_str) != 0) { fprintf(stderr, "Error: %s\n", mysql_error(&con_oboracle)); mysql_close(&con_oboracle); return 1; } printf("Table created successfully\n");Insert data.
Execute an SQL statement to insert data into the table. If the data is inserted successfully, print a success message. If the insertion fails, print an error message and exit the application. Perform the following steps:
Call the
sprintf_s()function to format and store an SQL statement in ansql_strarray. This SQL statement insertsid,name, andagecolumn values into thetest_tbl1table.Call the
mysql_query()function to execute the SQL statement.&con_oboracleis a pointer to the database connection object on which the SQL statement is executed.sql_stris the SQL statement to execute. Check whether the execution is successful. If the execution fails (with a non-zero return value), the following code block is executed.Call the
fprintf()function to print an error message to the standard error streamstderr. The first argument to thefprintf()function is the output stream, "Error: %s\n" is the formatted string, andmysql_error(&con_oboracle)is the actual argument that replaces%sin the formatted string.mysql_error(&con_oboracle)is the error message returned for getting thecon_oboracleconnection object.Close the connection to the database and release the resources of the connection object.
Use
return 1to exit themainfunction and return the value1if the data insertion fails, indicating that the application is abnormally terminated.
Print a success message if the data is successfully inserted.
The sample code is as follows:
sprintf_s(sql_str, "INSERT INTO test_tbl1 (id,name,age) VALUES (1,'Tom', 18),(2,'Jerry', 20),(3,'Bob', 22)"); if (mysql_query(&con_oboracle, sql_str) != 0) { fprintf(stderr, "Error: %s\n", mysql_error(&con_oboracle)); mysql_close(&con_oboracle); return 1; } printf("Data inserted successfully\n");Query data.
Execute an SQL statement to retrieve data from the table and print the retrieved data row by row. If the data is retrieved successfully, print a success message. If the retrieval fails, print an error message and exit the application. Perform the following steps:
Call the
sprintf_s()function to format and store an SQL statement in ansql_strarray. This SQL statement retrieves data of all columns in thetest_tbl1table.Call the
mysql_query()function to execute the SQL statement.&con_oboracleis a pointer to the database connection object on which the SQL statement is executed.sql_stris the SQL statement to execute. Check whether the execution is successful. If the execution fails (with a non-zero return value), the following code block is executed.Call the
fprintf()function to print an error message to the standard error streamstderr. The first argument to thefprintf()function is the output stream, "Error: %s\n" is the formatted string, andmysql_error(&con_oboracle)is the actual argument that replaces%sin the formatted string.mysql_error(&con_oboracle)is the error message returned for getting thecon_oboracleconnection object.Close the connection to the database and release the resources of the connection object.
Use
return 1to exit themainfunction and return the value1if the query fails, indicating that the application is abnormally terminated.
Use the
mysql_store_result()function to store the query result set in aMYSQL_RESstructure.&con_oboracleis a pointer to a database connection object from which the result set is obtained.Check whether the result set is empty. If the result set is empty, the query result set fails to be stored. In this case, execute the following code block.
Call the
fprintf()function to print an error message to the standard error streamstderr. The first argument to thefprintf()function is the output stream, "Error: %s\n" is the formatted string, andmysql_error(&con_oboracle)is the actual argument that replaces%sin the formatted string.mysql_error(&con_oboracle)is the error message returned for getting thecon_oboracleconnection object.Close the connection to the database and release the resources of the connection object.
Use
return 1to exit themainfunction and return the value1if the operation to store the query result set fails, indicating that the application is abnormally terminated.
Print a success message if the data is successfully retrieved.
Define the
rowvariable of theMYSQL_ROWtype to store data in each row.Call the
mysql_fetch_row()function to retrieve the data in the result set row by row and store the data in each row in therowvariable. Thewhileloop iterates until all rows in the result set are retrieved. In the loop, print the data of each row.row[0],row[1], androw[2]represent the values of the first, second, and third columns in the current row, respectively.
The sample code is as follows:
sprintf_s(sql_str, "SELECT * FROM test_tbl1"); if (mysql_query(&con_oboracle, sql_str) != 0) { fprintf(stderr, "Error: %s\n", mysql_error(&con_oboracle)); mysql_close(&con_oboracle); return 1; } MYSQL_RES* result = mysql_store_result(&con_oboracle); if (result == NULL) { fprintf(stderr, "Error: %s\n", mysql_error(&con_oboracle)); mysql_close(&con_oboracle); return 1; } printf("Data retrieved successfully\n"); MYSQL_ROW row; while ((row = mysql_fetch_row(result)) != NULL) { printf("id: %s, name: %s, age: %s\n", row[0], row[1], row[2]); }Exit the application.
Release resources and close the connection to the database. Perform the following steps:
Use
mysql_free_result(result)to release the result set resources stored by themysql_store_result()function.resultis a pointer to theMYSQL_RESstructure. It stores information and data of the query result set.Use
mysql_close(&con_oboracle)to close the connection to the database and release the resources occupied by the connection object.&con_oboracleis a pointer to the database connection object. You can call themysql_close()function to close the connection to the database and release the resources related to the connection object.Use
return 0;to indicate the end of the normal execution of the application, and return0as the exit status of the application.
The sample code is as follows:
mysql_free_result(result); mysql_close(&con_oboracle); printf("finish\n"); return 0; }
Complete code
#include <stdio.h>
#include <stdlib.h>
#include <mysql.h>
#pragma comment(lib, "Shlwapi.lib")
#pragma comment( lib, "ws2_32.lib" )
#pragma comment(lib, "Crypt32.lib")
#pragma comment(lib, "Secur32.lib")
#pragma comment(lib, "obclnt.lib")
int main() {
MYSQL con_oboracle;
char sql_str[1024] = { 0 };
if (NULL == mysql_init(&con_oboracle)) {
fprintf(stderr, "Error: %s\n", mysql_error(&con_oboracle));
return 1;
}
printf("mysql_init() success\n");
if (NULL == mysql_real_connect(&con_oboracle, "your_ip", "your_user", "your_password", "your_schema", your_port, NULL, 0)) {
fprintf(stderr, "Error: %s\n", mysql_error(&con_oboracle));
return 1;
}
printf("mysql_real_connect() success\n");
sprintf_s(sql_str, "CREATE TABLE test_tbl1(id NUMBER PRIMARY KEY, name VARCHAR2(50),age NUMBER NOT NULL)");
if (mysql_query(&con_oboracle, sql_str) != 0) {
fprintf(stderr, "Error: %s\n", mysql_error(&con_oboracle));
mysql_close(&con_oboracle);
return 1;
}
printf("Table created successfully\n");
sprintf_s(sql_str, "INSERT INTO test_tbl1 (id,name,age) VALUES (1,'Tom', 18),(2,'Jerry', 20),(3,'Bob', 22)");
if (mysql_query(&con_oboracle, sql_str) != 0) {
fprintf(stderr, "Error: %s\n", mysql_error(&con_oboracle));
mysql_close(&con_oboracle);
return 1;
}
printf("Data inserted successfully\n");
sprintf_s(sql_str, "SELECT * FROM test_tbl1");
if (mysql_query(&con_oboracle, sql_str) != 0) {
fprintf(stderr, "Error: %s\n", mysql_error(&con_oboracle));
mysql_close(&con_oboracle);
return 1;
}
MYSQL_RES* result = mysql_store_result(&con_oboracle);
if (result == NULL) {
fprintf(stderr, "Error: %s\n", mysql_error(&con_oboracle));
mysql_close(&con_oboracle);
return 1;
}
printf("Data retrieved successfully\n");
MYSQL_ROW row;
while ((row = mysql_fetch_row(result)) != NULL) {
printf("id: %s, name: %s, age: %s\n", row[0], row[1], row[2]);
}
mysql_free_result(result);
mysql_close(&con_oboracle);
printf("finish\n");
return 0;
}
References
For more information about OceanBase Connector/C, see OceanBase Connector/C.