This topic describes how to use the SqlSugar framework, OceanBase Connector/ODBC, and OceanBase Cloud to build an application for basic database operations, such as table creation, data insertion, and data query.
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 Visual Studio, with the NuGet Package Manager and .NET Framework components enabled.
You have installed the OceanBase Connector/ODBC driver.
Note
You can download the installation package of OceanBase Connector/ODBC for Windows from [OceanBase Download Center](https://en.oceanbase.com/softwarecenter-cloud). Follow the default instructions to install OceanBase Connector/ODBC for Windows.
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 sqlsugar-oceanbase-odbc 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 sqlsugar-oceanbase-odbc folder, select the project file sqlsugar-oceanbase-odbc.sln or sqlsugar-oceanbase-odbc.csproj, and click Open.
Step 2: Install SqlSugar-related packages
On the top menu bar of Visual Studio Community 2019, choose Tools > NuGet Package Manager > Manage NuGet Packages for Solution.
On the Browse tab, enter
sqlsugarin the search box to search for and download theSqlSugarpackage.On the Browse tab, enter
sqlsugar.odbcin the search box to search for and download theSqlSugar.OdbcandSqlSugar.OdbcCorepackages.After the installation, you can use the relevant namespaces and types of SqlSugar in the project code files.
Step 3: Configure a data source
Check whether the OceanBase Connector/ODBC driver is installed.
Choose Control Panel > System and Security > Administrative Tools > ODBC Data Sources (64-bit) > Drivers. The OceanBase Connector/ODBC driver is displayed if it is installed.
Create a data source.
Choose User DSN > Add. Select the driver, and click Finish.
In the window that appears, enter the data source name
test_oboraclein Name and the description in Description, and then click Next.In the pop-up window, enter the obtained database connection information mentioned in the "Prerequisites" section, and click Next. You can also set the initialization statement, TLS, cursor, and result set.
Note
After you fill in the database connection information, you can click Test DSN to check whether the data source can be connected successfully.
Click Finish. The data source is added. Then, click OK.
Step 4: Modify the data source in the sqlsugar-oceanbase-odbc project
Modify the data source in the Program.cs file based on the data source created in Step 3: Configure a data source.
Here is an example:
Replace your_dsn with the data source test_oboracle that you created in Step 3: Configure a data source.
public static string ConnectionString = "DSN=test_oboracle";
Step 5: 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 6: Run the application
Choose Debug > Start Debugging or choose Debug > Start Without Debugging to run the application.
Step 7: 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 sqlsugar-oceanbase-odbc.zip.
Decompress the package to obtain a folder named sqlsugar-oceanbase-odbc. The directory structure is as follows:
sqlsugar-oceanbase-odbc
├─ Program.cs
├─ sqlsugar-oceanbase-odbc.csproj
└─ sqlsugar-oceanbase-odbc.sln
The files and directories are described as follows:
Program.cs: the main program file of the project, which contains the entry to the project and the source code that defines the data table and implements data table operations.sqlsugar-oceanbase-odbc.csproj: the main project file in Visual Studio, which defines the configurations, dependencies, and build information of the project.sqlsugar-oceanbase-odbc.sln: the solution file in Visual Studio, which contains information about the project and its related projects for unified management and build of multiple projects.
Code in Program.cs
Code in the Program.cs file shows how to use SqlSugar to operate OceanBase Cloud, such as creating tables, inserting data, and querying data. Besides, the AopEvents object is used to set the callback function for events such as log execution, which facilitates debugging and troubleshooting.
Perform the following steps to configure the Program.cs file:
Reference namespaces.
Use the
usingkeyword to reference theSystem,SqlSugar,System.Linq,System.Data, andSystem.Data.Odbcnamespaces, so that related data access classes and database operation classes and methods can be referenced.The sample code is as follows:
using System; using SqlSugar; using System.Linq; using System.Data; using System.Data.Odbc;Define the namespace for placing related classes and methods.
Define the
GbaseTestnamespace, in which theProgramandTestEntityclasses are defined.The sample code is as follows:
namespace GbaseTest { internal class Program { ... ... } public class TestEntity { ... ... } }Define the
Programclass that contains the main logic of the application.Perform the following steps:
Define a public static variable
ConnectionStringof the string type to store the database connection string. The variable can be accessed anywhere in the current assembly.DSN=your_dsnindicates that an ODBC connection is used and the data source isyour_dsn.Notice
To run the application, replace
your_dsnwith the name of the data source that you created in Step 3.Define the
Mainmethod as the entry to the application. It contains the main logic of the application.try-catchblock:- Use the
trykeyword to wrap a piece of code that may throw an exception, theusingstatement, and database operations. - Use the
catchkeyword to capture exceptions and handle them.
- Use the
- Finally, output
Program End.before the application exits.
The sample code is as follows:
internal class Program { public static string ConnectionString = "DSN=your_dsn"; static void Main(string[] args) { try { using (...) { // Database operations } } catch (Exception ex) { ... ... } Console.WriteLine("Program End."); } }Use the
usingstatement.Use
ConnectionConfigto configure the database connection information and other options, including the database type ODBC, the connection stringConnectionString, the primary key typeAttribute, automatic connection closing, and the callback function for log execution events. Use theSqlSugarClientobject to conveniently perform database operations, including creating tables, inserting data, and querying data. Use theusingstatement to automatically release related resources, including closing the database connection. Perform the following steps:Create an
SqlSugarClientobject and assign it to the variable nameddb.Create a connection configuration instance and use the object initializer to initialize its attributes such as
DbType,ConnectionString,InitKeyType,IsAutoCloseConnection, andAopEvents.Set the database type to ODBC.
Set the connection string to
ConnectionString.Set the primary key type to
Attribute.Enable automatic connection closing.
Use
AopEventsto set the callback function for log execution events. Set the implementation logic for the callback function, in whichsqlindicates the executed SQL statement andpindicates the list of parameters in the SQL statement. In the implementation logic, the SQL statement and its parameter list are printed to the console.
The sample code is as follows:
using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { DbType = SqlSugar.DbType.Odbc, ConnectionString = ConnectionString, InitKeyType = InitKeyType.Attribute, IsAutoCloseConnection = true, AopEvents = new AopEvents { OnLogExecuting = (sql, p) => { Console.WriteLine(sql); Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value))); } } }))Perform database operations.
Call the
SqlSugarClient.Ado.ExecuteCommandmethod to execute SQL statements that create tables and insert data, and call theSqlSugarClient.Ado.SqlQuerymethod to query data and traverse query results. Use theSqlSugarClientobject to conveniently perform database operations, including creating tables, inserting data, and querying data. Perform the following steps:Output a prompt to indicate that table creation starts.
Execute an SQL statement to create the
test_tbl1table that contains two columns:idandname.Output a prompt to indicate that data insertion starts.
Define the
tableNamevariable to store a table name, and assign the valuetest_tbl1to the variable.Execute an SQL statement to insert three records into the
test_tbl1table: "1, John", "2, Jack", and "3, Amy".Output a prompt to indicate that data query starts.
Execute an SQL statement to query all data in the
test_tbl1table, and assign the query results to thedatavariable.TestEntityis the entity class of the query result.Output a prompt to indicate that query result traversal starts.
Traverse the query results and assign each record to the
itemvariable. Output theidandnamefields for each record.
The sample code is as follows:
{ Console.WriteLine("Create Table:"); db.Ado.ExecuteCommand("CREATE TABLE test_tbl1(id NUMBER PRIMARY KEY, name VARCHAR2(50))"); Console.WriteLine("Insert Data:"); string tableName = "test_tbl1"; int intValue = db.Ado.ExecuteCommand($"INSERT INTO {tableName} (id, name) VALUES (1, 'John'), (2, 'Jack'), (3, 'Amy')"); Console.WriteLine("Query Data"); var data = db.Ado.SqlQuery<TestEntity>($"SELECT * FROM {tableName}"); Console.WriteLine("Query Results:"); foreach (var item in data) { Console.WriteLine($"id: {item.id}, name: {item.name}"); } }Use the
catchkeyword to capture exceptions and handle them.When exceptions occur in the application, information about the exceptions will be output. The exceptions, once captured, will help debug and locate problems, ensuring the robustness and reliability of the application. Perform the following steps:
Use the
catchkeyword to capture an exception and assign the exception to theexvariable, which is an instance of theExceptionclass or one of its subclasses.Output a prompt to indicate that an exception occurs in the application.
Convert the captured exception object to a string and output the string. The string contains information such as the type, message, and stack trace of the exception.
The sample code is as follows:
catch (Exception ex) { Console.WriteLine("Program Exception:"); Console.WriteLine(ex.ToString()); }Define the
TestEntityclass.Define the
TestEntityclass with two attributes:idandname, which represent theidandnamefields of an entity object. Perform the following steps:Define a public class named
TestEntity.Define a public integer attribute named
id, which represents theidfield of an entity object. This field can be read and set by calling thegetandsetmethods of the attribute.Define a public string attribute named
name, which represents thenamefield of the entity object. This field can be read and set by calling thegetandsetmethods of the attribute.
The sample code is as follows:
public class TestEntity { public int id { get; set; } public string name { get; set; } }
Complete code
using System;
using SqlSugar;
using System.Linq;
using System.Data;
using System.Data.Odbc;
namespace GbaseTest
{
internal class Program
{
public static string ConnectionString = "DSN=your_dsn";
static void Main(string[] args)
{
try
{
using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
DbType = SqlSugar.DbType.Odbc,
ConnectionString = ConnectionString,
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true,
AopEvents = new AopEvents
{
OnLogExecuting = (sql, p) =>
{
Console.WriteLine(sql);
Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));
}
}
}))
{
Console.WriteLine("Create Table:");
db.Ado.ExecuteCommand("CREATE TABLE test_tbl1(id NUMBER PRIMARY KEY, name VARCHAR2(50))");
Console.WriteLine("Insert Data:");
string tableName = "test_tbl1";
int intValue = db.Ado.ExecuteCommand($"INSERT INTO {tableName} (id, name) VALUES (1, 'John'), (2, 'Jack'), (3, 'Amy')");
Console.WriteLine("Query Data");
var data = db.Ado.SqlQuery<TestEntity>($"SELECT * FROM {tableName}");
Console.WriteLine("Query Results:");
foreach (var item in data)
{
Console.WriteLine($"id: {item.id}, name: {item.name}");
}
}
}
catch (Exception ex)
{
Console.WriteLine("Program Exception:");
Console.WriteLine(ex.ToString());
}
Console.WriteLine("Program End.");
}
}
public class TestEntity
{
public int id { get; set; }
public string name { get; set; }
}
}
References
For more information about OceanBase Connector/ODBC, see OceanBase Connector/ODBC.
Download the sqlsugar-oceanbase-odbc sample project