This topic introduces how to build an application by using the SqlSugar framework, OceanBase Connector/ODBC, and OceanBase Database. It also covers the use of the application for fundamental database operations, including table creation, data insertion, and data query.
Prerequisites
You have installed OceanBase Database and created an Oracle tenant. For more information about how to install OceanBase Database, see Deployment overview.
You have installed Visual Studio, with the NuGet Package Manager and .NET Framework components being 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. To install OceanBase Connector/ODBC for Windows, follow the default instructions.
Procedure
Note
The steps outlined in this topic are for the Windows environment. If you are using a different operating system or compiler, the steps may vary slightly.
- Open the
sqlsugar-oceanbase-odbcproject. - Install SqlSugar-related packages.
- Configure a data source.
- Modify the data source in the
sqlsugar-oceanbase-odbcproject. - Build the project.
- Run the application.
- Check the output.
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 under Get started. Alternatively, click Continue without code in the lower right corner, and choose File > Open > Project/Solution in the menu bar of the page that appears.
Browse to the sqlsugar-oceanbase-odbc folder, select the project file
sqlsugar-oceanbase-odbc.slnorsqlsugar-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 the SqlSugar package.On Browse tab, enter
sqlsugar.odbcin the search box to search for and download theSqlSugar.OdbcandSqlSugar.OdbcCorepackages.After installation, you can use the relevant namespaces and types of SqlSugar in the project code files.
Step 3: Configure a data source
Obtain the database connection information.
Contact the deployment personnel or administrator of OceanBase Database to obtain the database connection string.
Here is an example:
obclient -hxxx.xxx.xxx.xxx -P2881 -usys@oracle001 -p******where
-hspecifies the IP address for connecting to OceanBase Database. For connection through OceanBase Database Proxy (ODP), this parameter is the IP address of an ODP. For direct connection, this parameter is the IP address of an OBServer node.-Pspecifies the port for connecting to OceanBase Database. For connection through ODP, the default value is2883, which can be customized when ODP is deployed. For direct connection, the default value is2881, which can be customized when OceanBase Database is deployed.-uspecifies the tenant account. For connection through ODP, the tenant account can be in theusername@tenant name#cluster nameorcluster name:tenant name:usernameformat. For direct connection, the tenant account is in theusername@tenant nameformat.-pspecifies the account password.
For more information about connection strings, see Connect to an OceanBase tenant by using OBClient.
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 in Name and description in Description, and then click Next.
Enter the database connection information in the pop-up window, 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.
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: View 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 program.
Project code introduction
Click sqlsugar-oceanbase-odbc to download the project code, which is a compressed file named sqlsugar-oceanbase-odbc.zip.
After decompressing it, you will find 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
Here is a breakdown of the files and directories:
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 Database, 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.
To configure the Program.cs file, perform the following steps:
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 program.The steps are as follows:
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 program, replace
your_dsnwith the name of the data source that you created in Step 3.Define the
Mainmethod as the entry to the program. It contains the main logic of the program.- Define the
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 program ends.
- Define the
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."); } }Define 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 perform database operations, including creating tables, inserting data, and querying data. Use theusingstatement to automatically release related resources, including closing the database connection. The steps are as follows:Create a
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. The steps are as follows: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. Assign thetest_tbl1value to it.Execute an SQL statement to insert three records into the
test_tbl1table:1, 'John',2, 'Jack', and3, '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 program, information about the exceptions will be output. The exceptions, once captured, will help debug and locate problems, ensuring the robustness and reliability of the program. The steps are as follows:
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 program.
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. The steps are as follows: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 an 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 examples
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 how to connect to OceanBase Database, see Overview of connection methods.
For more information about OceanBase Connector/ODBC, see OceanBase Connector/ODBC.
Download the sqlsugar-oceanbase-odbc sample project