OceanBase
English日本語简体中文
Docs Home
Products
Integrations
Release Notes

Databases

OceanBase DatabaseOceanBase Cloud OceanBase Best Practices

Tools

OceanBase Cloud PlatformOceanBase Migration ServiceOceanBase Developer CenterOceanBase Migration AssessmentOceanBase Admin ToolOceanBase Loader and DumperOceanBase DeployerKubernetes operator for OceanBaseOceanBase Diagnostic Tool OceanBase Binlog Service

Connectors and Middleware

OceanBase Database Proxy OceanBase Connector/C OceanBase Connector/J OceanBase Connector/ODBC OceanBase Connector/NETOceanBase Command-Line Client

Databases

OceanBase DatabaseOceanBase Cloud OceanBase Best Practices

Connectors and Middleware

OceanBase Database Proxy OceanBase Connector/C OceanBase Connector/J OceanBase Connector/ODBC OceanBase Connector/NETOceanBase Command-Line Client

Tools

OceanBase Cloud PlatformOceanBase Migration ServiceOceanBase Developer CenterOceanBase Migration AssessmentOceanBase Admin ToolOceanBase Loader and DumperOceanBase DeployerKubernetes operator for OceanBaseOceanBase Diagnostic Tool OceanBase Binlog Service
OceanBase DatabaseOceanBase Cloud ToolsConnectors and MiddlewareLifecycle Support Policy

OceanBase Database

  • Overview of the ecosystem
  • ORM frameworks
    • Java
      • Spring Boot
      • Spring Batch
      • Use Spring JDBC to connect to OceanBase Database
      • Spring Data JPA
      • Hibernate
      • MyBatis
      • jOOQ
    • Python
      • Use SQLAlchemy to connect to OceanBase Database
      • Connect to OceanBase Database by using peewee
      • Use Tortoise ORM to connect to OceanBase Database
    • Go
      • Connect to OceanBase Database by using GORM
      • beego ORM
    • Rust
      • SeaORM Connection to OceanBase Database
      • Diesel Connection to OceanBase Database
    • Ruby
      • Active Record
      • Sequel Connection to OceanBase Database
      • Connect to OceanBase Database by using Ruby on Rails
    • Node.js
      • Sequelize
      • TypeORM
      • Prisma
      • Drizzle
    • C#
      • Dapper
      • SqlSugar
      • FreeSQL
    • PHP
      • Connect to OceanBase Database by using the Yii 2.0 ORM
      • Connect to OceanBase Database by using Laravel Eloquent ORM
      • CakePHP
  • Database version management
    • Liquibase
    • Flyway
  • Data integration
    • Flink
      • Apache Flink
      • Flink DirectLoad
      • Flink Connector OceanBase
    • dbt
    • SeaTunnel
    • Maxwell
    • Debezium
    • Spark Catalog
    • NiFi
    • Qlik Replicate
    • RisingWave CDC
    • Flume
    • Migrate data from SQL Server to OceanBase Database by using MySQL Workbench
  • SQL development
    • WebLogic
    • DBeaver
    • Navicat
    • DataGrip
    • TablePlus
    • DMS
  • Orchestration and scheduling
    • Airflow
    • PowerJob
    • DolphinScheduler
    • Linkis
  • Visualization tools
    • Superset
    • Excel
    • Power BI
    • Quick BI
    • Tableau
    • GuanData
    • vividime
    • DataV
    • Metabase
    • Redash
    • FineReport
  • Database management
    • NineData
    • Bytebase
    • DataHub
    • Zabbix
  • AI
    • OpenAI
    • Qwen
    • LangChain
    • LlamaIndex
    • Dify
    • n8n
    • Trae
    • SpringAI
    • Cline
    • Cursor
    • Continue
    • MCP Toolbox
    • CamelAI
    • Firecrawl
    • Hugging Face
    • Ollama
    • Google Gemini
    • Cloudflare Workers AI
    • DB GPT
    • Jina AI
    • Augment Code
    • Claude Code
    • Kiro
    • GPT4All
  • Application
    • Ghost
    • Jira
    • Seata
    • SAP Crystal Reports
  • Middleware
    • Apache Pulsar

Download PDF

Document Feedback
  1. Documentation Center
  2. OceanBase Database
  3. master

Connect to OceanBase Database by using SqlSugar

Last Updated:2026-09-04 07:40:45

Prerequisites
Procedure
Step 1: Create a new project
Step 2: Install the required NuGet packages
Step 3: Configure the database connection
Step 4: Create a data model
Step 5: Implement the data access layer
Step 6: Implement the main program
Run the program
References

Applicability

SqlSugar is applicable to OceanBase Database in MySQL mode.

SqlSugar is a powerful and easy-to-use ORM framework that supports the .NET platform. This topic describes how to use SqlSugar to connect to OceanBase Database in MySQL mode.

Prerequisites

  • You have installed .NET SDK 6.0 or later.
  • You have installed Visual Studio or VS Code.
  • You have deployed OceanBase Database and created a MySQL tenant.

Procedure

  1. Create a new project.
  2. Install the required NuGet packages.
  3. Configure the database connection.
  4. Create a data model.
  5. Implement the data access layer.
  6. Run the sample program.

Step 1: Create a new project

  1. Run the following command in the terminal to create a new console application:

    dotnet new console -n SqlSugarOceanBaseDemo
    cd SqlSugarOceanBaseDemo
    

Step 2: Install the required NuGet packages

  1. Install the SqlSugar core package and the MySQL database provider:

    # ORM core package
    dotnet add package SqlSugarCore
    
    # Database provider
    dotnet add package MySql.Data
    
    # Configuration-related packages
    dotnet add package Microsoft.Extensions.Configuration --version 8.0.0
    dotnet add package Microsoft.Extensions.Configuration.FileExtensions --version 8.0.0
    dotnet add package Microsoft.Extensions.Configuration.Json --version 8.0.0
    
    # Password encryption
    dotnet add package BCrypt.Net-Next --version 4.0.3
    

Step 3: Configure the database connection

  1. Create an appsettings.json file and add the database connection string:

    {
      "ConnectionStrings": {
        "DefaultConnection": "Server=your_server;Port=2881;Database=your_database;Uid=your_username;Pwd=your_password;"
      }
    }
    
  2. Modify the project file (.csproj) to ensure that appsettings.json is copied to the output directory:

    <ItemGroup>
      <None Update="appsettings.json">
        <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      </None>
    </ItemGroup>
    

Step 4: Create a data model

  1. Create a Models folder and add a User.cs class:

    using SqlSugar;
    
    namespace SqlSugarOceanBaseDemo.Models;
    
    [SugarTable("users")]
    public class User
    {
        [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
        public int Id { get; set; }
    
        [SugarColumn(Length = 50, IsNullable = false)]
        public string Username { get; set; }
    
        [SugarColumn(Length = 100, IsNullable = false)]
        public string Email { get; set; }
    
        [SugarColumn(Length = 255, IsNullable = false)]
        public string PasswordHash { get; set; }
    
        [SugarColumn(IsNullable = false)]
        public DateTime CreatedAt { get; set; }
    
        [SugarColumn(IsNullable = true)]
        public DateTime? UpdatedAt { get; set; }
    }
    

Step 5: Implement the data access layer

  1. Create a Services folder and add a DatabaseContext.cs class:

    using Microsoft.Extensions.Configuration;
    using SqlSugar;
    using System;
    using System.IO;
    
    namespace SqlSugarOceanBaseDemo.Services;
    
    public class DatabaseContext
    {
        public SqlSugarScope Db { get; private set; }
    
        public DatabaseContext(IConfiguration configuration)
        {
            Db = new SqlSugarScope(new ConnectionConfig()
            {
                ConnectionString = configuration.GetConnectionString("DefaultConnection"),
                DbType = DbType.MySql,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute
            },
            db =>
            {
                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    Console.WriteLine($"SQL: {sql}");
                    if (pars != null)
                    {
                        foreach (var param in pars)
                        {
                            Console.WriteLine($"  -> {param.ParameterName}: {param.Value}");
                        }
                    }
                };
    
                db.Aop.OnError = (exp) =>
                {
                    Console.WriteLine($"Error: {exp.Message}");
                    return true;
                };
    
                db.Aop.OnLogExecuted = (sql, pars) =>
                {
                    Console.WriteLine($"Execution time: {db.Ado.SqlExecutionTime.TotalMilliseconds}ms");
                };
    
                db.InitKeyType = InitKeyType.Attribute;
            };
    
            Db.CodeFirst.InitTables(typeof(Models.User));
        }
    }
    
  2. Create a Repositories folder and add a UserRepository.cs class:

    using SqlSugar;
    using SqlSugarOceanBaseDemo.Models;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    
    namespace SqlSugarOceanBaseDemo.Repositories;
    
    public class UserRepository
    {
        private readonly ISqlSugarClient _db;
    
        public UserRepository(ISqlSugarClient db)
        {
            _db = db;
        }
    
        public async Task<List<User>> GetAllUsersAsync()
        {
            return await _db.Queryable<User>().ToListAsync();
        }
    
        public async Task<User> GetUserByIdAsync(int id)
        {
            return await _db.Queryable<User>().FirstAsync(u => u.Id == id);
        }
    
        public async Task<int> CreateUserAsync(User user)
        {
            user.CreatedAt = DateTime.UtcNow;
            return await _db.Insertable(user).ExecuteReturnIdentityAsync();
        }
    
        public async Task<bool> UpdateUserAsync(User user)
        {
            user.UpdatedAt = DateTime.UtcNow;
            return await _db.Updateable(user).ExecuteCommandHasChangeAsync();
        }
    
        public async Task<bool> DeleteUserAsync(int id)
        {
            return await _db.Deleteable<User>().Where(u => u.Id == id).ExecuteCommandHasChangeAsync();
        }
    }
    

Step 6: Implement the main program

Modify the Program.cs file:

using Microsoft.Extensions.Configuration;
using SqlSugarOceanBaseDemo.Models;
using SqlSugarOceanBaseDemo.Repositories;
using SqlSugarOceanBaseDemo.Services;
using System;
using System.IO;
using System.Threading.Tasks;

var configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .Build();

var dbContext = new DatabaseContext(configuration);
var userRepository = new UserRepository(dbContext.Db);

var newUser = new User
{
    Username = "testuser",
    Email = "test@example.com",
    PasswordHash = BCrypt.Net.BCrypt.HashPassword("your_secure_password")
};

try
{
    var createdUser = await userRepository.CreateUserAsync(newUser);
    Console.WriteLine($"User created with ID: {createdUser.Id}");

    var user = await userRepository.GetUserByIdAsync(createdUser.Id);
    if (user != null)
    {
        Console.WriteLine($"Retrieved user: {user.Username}, Email: {user.Email}");

        user.Username = "updated_username";
        var updated = await userRepository.UpdateUserAsync(user);
        Console.WriteLine($"User updated: {updated}");

        var users = await userRepository.GetAllUsersAsync();
        Console.WriteLine($"Total users: {users.Count}");

        var deleted = await userRepository.DeleteUserAsync(user.Id);
        Console.WriteLine($"User deleted: {deleted}");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"An error occurred: {ex.Message}");
}

Run the program

  1. Make sure that the database connection string in the appsettings.json file is updated.

  2. Run the following command in the terminal:

    dotnet run
    

References

  • SqlSugar documentation
  • .NET database access best practices
  • OceanBase documentation

Previous topic

Dapper
Last

Next topic

FreeSQL
Next
on this page
Prerequisites
Procedure
Step 1: Create a new project
Step 2: Install the required NuGet packages
Step 3: Configure the database connection
Step 4: Create a data model
Step 5: Implement the data access layer
Step 6: Implement the main program
Run the program
References