OceanBase logo

OceanBase

A unified distributed database ready for your transactional, analytical, and AI workloads.

Product Overview
DEPLOY YOUR WAY

OceanBase Cloud

The best way to deploy and scale OceanBase

OceanBase Enterprise

Run and manage OceanBase on your infra

TRY OPEN SOURCE

OceanBase Community Edition

The free, open-source distributed database

OceanBase seekdb

Open source AI native search database

Customer Stories

Real-world success stories from enterprises across diverse industries.

View All
BY USE CASES

Mission-Critical Transactions

Global & Multicloud Application

Elastic Scaling for Peak Traffic

Real-time Analytics

Active Geo-redundancy

Database Consolidation

Resources

Comprehensive knowledge hub for OceanBase.

Blog

Live Demos

Training & Certification

Documentation

Official technical guides, tutorials, API references, and manuals for all OceanBase products.

View All
PRODUCTS

OceanBase Cloud

OceanBase Database

Tools

Connectors and Middleware

QUICK START

OceanBase Cloud

OceanBase Database

BEST PRACTICES

Practical guides for utilizing OceanBase more effectively and conveniently

Company

Learn more about OceanBase – our company, partnerships, and trust and security initiatives.

About OceanBase

Partner

Trust Center

Contact Us

International - English
中国站 - 简体中文
日本 - 日本語
Sign In
Start on Cloud

OceanBase

A unified distributed database ready for your transactional, analytical, and AI workloads.

Product Overview
DEPLOY YOUR WAY

OceanBase Cloud

The best way to deploy and scale OceanBase

OceanBase Enterprise

Run and manage OceanBase on your infra

TRY OPEN SOURCE

OceanBase Community Edition

The free, open-source distributed database

OceanBase seekdb

Open source AI native search database

Customer Stories

Real-world success stories from enterprises across diverse industries.

View All
BY USE CASES

Mission-Critical Transactions

Global & Multicloud Application

Elastic Scaling for Peak Traffic

Real-time Analytics

Active Geo-redundancy

Database Consolidation

Comprehensive knowledge hub for OceanBase.

Blog

Live Demos

Training & Certification

Documentation

Official technical guides, tutorials, API references, and manuals for all OceanBase products.

View All
PRODUCTS
OceanBase CloudOceanBase Database
ToolsConnectors and Middleware
QUICK START
OceanBase CloudOceanBase Database
BEST PRACTICES

Practical guides for utilizing OceanBase more effectively and conveniently

Learn more about OceanBase – our company, partnerships, and trust and security initiatives.

About OceanBase

Partner

Trust Center

Contact Us

Start on Cloud
编组
All Products
    • Databases
    • iconOceanBase Database
    • iconOceanBase Cloud
    • iconOceanBase Tugraph
    • iconInteractive Tutorials
    • iconOceanBase Best Practices
    • Tools
    • iconOceanBase Cloud Platform
    • iconOceanBase Migration Service
    • iconOceanBase Developer Center
    • iconOceanBase Migration Assessment
    • iconOceanBase Admin Tool
    • iconOceanBase Loader and Dumper
    • iconOceanBase Deployer
    • iconKubernetes operator for OceanBase
    • iconOceanBase Diagnostic Tool
    • iconOceanBase Binlog Service
    • Connectors and Middleware
    • iconOceanBase Database Proxy
    • iconEmbedded SQL in C for OceanBase
    • iconOceanBase Call Interface
    • iconOceanBase Connector/C
    • iconOceanBase Connector/J
    • iconOceanBase Connector/ODBC
    • iconOceanBase Connector/NET
icon

OceanBase Database

SQL - V4.4.2

    Download PDF

    OceanBase logo

    The Unified Distributed Database for the AI Era.

    Follow Us
    Products
    OceanBase CloudOceanBase EnterpriseOceanBase Community EditionOceanBase seekdb
    Resources
    DocsBlogLive DemosTraining & CertificationTicket
    Company
    About OceanBaseTrust CenterLegalPartnerContact Us
    Follow Us

    © OceanBase 2026. All rights reserved

    Cloud Service AgreementPrivacy PolicySecurity
    Contact Us
    Document Feedback
    1. Documentation Center
    2. OceanBase Database
    3. SQL
    4. V4.4.2
    iconOceanBase Database
    SQL - V 4.4.2
    SQL
    KV
    • V 4.6.0
    • V 4.4.2
    • V 4.3.5
    • V 4.3.3
    • V 4.3.1
    • V 4.3.0
    • V 4.2.5
    • V 4.2.2
    • V 4.2.1
    • V 4.2.0
    • V 4.1.0
    • V 4.0.0
    • V 3.1.4 and earlier

    Connect to OceanBase Database by using Drizzle ORM

    Last Updated:2026-04-09 08:31:39  Updated
    share
    What is on this page
    Prerequisites
    Procedure
    Step 1: Check the versions of Node.js and npm
    Step 2: Install the required dependencies
    Step 2: Configure the database connection
    Step 3: Obtain the connection information of OceanBase Database
    Step 3: Define the data table model
    Step 4: Create a database connection
    Step 5: CRUD operations example
    Run the example
    References

    folded

    share

    Drizzle ORM is a lightweight, type-safe Object-Relational Mapping (ORM) designed for TypeScript. This guide walks you through connecting to OceanBase Database's MySQL-compatible mode by using Drizzle ORM.

    Prerequisites

    • You have installed Node.js 16.0.0 or later.
    • You have installed the npm or yarn package manager.
    • You have deployed OceanBase Database and created a MySQL-compatible tenant.

    Procedure

    1. Check the versions of Node.js and npm.
    2. Install the required dependencies.
    3. Obtain the connection information of OceanBase Database.
    4. Create and configure the project.
    5. Run the sample program.

    Step 1: Check the versions of Node.js and npm

    Open the terminal and run the following commands to check the versions of Node.js and npm:

    node -v
    npm -v
    

    Step 2: Install the required dependencies

    mkdir drizzle-oceanbase-demo
    cd drizzle-oceanbase-demo
    npm init -y
    npm install drizzle-orm mysql2
    npm install -D typescript @types/node ts-node
    npx tsc --init
    

    Step 2: Configure the database connection

    Create a .env file in the project root directory and fill in the database connection information:

    DB_HOST=your_host
    DB_PORT=2881
    DB_USER=your_username
    DB_PASSWORD=your_password
    DB_NAME=your_database
    

    Step 3: Obtain the connection information of OceanBase Database

    Contact the deployment personnel or administrator of OceanBase Database to obtain the corresponding database connection information.

    mysql -h$host -P$port -u$user_name -p$password -D$database_name
    

    Parameters:

    • $host: the IP address for connecting to OceanBase Database.
    • $port: the port number for connecting to OceanBase Database.
    • $database_name: the name of the database to be accessed.
    • $user_name: the username for connecting to the tenant.
    • $password: the password for the account.

    Step 3: Define the data table model

    Create a src/db/schema.ts file:

    import { mysqlTable, int, varchar, timestamp, index } from 'drizzle-orm/mysql-core';
    
    export const users = mysqlTable('users', {
      id: int('id').primaryKey().autoincrement(),
      username: varchar('username', { length: 255 }).notNull(),
      email: varchar('email', { length: 255 }).notNull().unique(),
      passwordHash: varchar('password_hash', { length: 255 }).notNull(),
      createdAt: timestamp('created_at').defaultNow().notNull(),
      updatedAt: timestamp('updated_at').defaultNow().onUpdateNow().notNull(),
    }, (table) => ({
    // Add an index on the email field
      emailIdx: index('email_idx').on(table.email),
    }));
    

    Create the table in OceanBase Database:

    CREATE TABLE IF NOT EXISTS users (
      id INT AUTO_INCREMENT PRIMARY KEY,
      username VARCHAR(255) NOT NULL,
      email VARCHAR(255) NOT NULL UNIQUE,
      password_hash VARCHAR(255) NOT NULL,
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
      updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL
    );
    

    Step 4: Create a database connection

    Create src/db/index.ts:

    import { drizzle } from 'drizzle-orm/mysql2';
    import mysql from 'mysql2/promise';
    import * as schema from './schema';
    import * as dotenv from 'dotenv';
    
    // Load environment variables
    dotenv.config();
    
    const poolConnection = mysql.createPool({
      host: process.env.DB_HOST,
      port: parseInt(process.env.DB_PORT || '2881'),
      user: process.env.DB_USER,
      password: process.env.DB_PASSWORD,
      database: process.env.DB_NAME,
      waitForConnections: true,
      connectionLimit: 10,
      queueLimit: 0,
      timezone: '+08:00',
    // Add these options for better compatibility
      multipleStatements: true,
      supportBigNumbers: true,
      bigNumberStrings: true
    });
    
    console.log('Connecting to database at:', {
    host: process.env.DB_HOST,
    port: process.env.DB_PORT,
    user: process.env.DB_USER,
    database: process.env.DB_NAME
    });
    
    export const db = drizzle(poolConnection, {
      schema,
      mode: 'default'
    });
    

    Step 5: CRUD operations example

    Create src/index.ts:

    import { db } from './db';
    import { users } from './db/schema';
    import { eq } from 'drizzle-orm';
    
    async function main() {
      try {
        // Test the connection first
        await db.select().from(users).limit(1);
        console.log('Successfully connected to the database');
    
        // Create user
        const insertResult = await db.insert(users).values({
          username: 'testuser',
          email: 'test@example.com',
          passwordHash: 'hashed_password',
        });
        console.log('Insert result:', insertResult);
    
        // Get the inserted user
        const [newUser] = await db.select().from(users).where(eq(users.email, 'test@example.com'));
        console.log('Created user:', newUser);
    
        // Query user
        const [user] = await db.select().from(users).where(eq(users.id, newUser.id));
        console.log('Retrieved user:', user);
    
        // Update user
        const updateResult = await db.update(users)
          .set({ email: 'new.email@example.com' })
          .where(eq(users.id, newUser.id));
        console.log('Update result:', updateResult);
    
        // Get the updated user
        const [updatedUser] = await db.select().from(users).where(eq(users.id, newUser.id));
        console.log('Updated user:', updatedUser);
    
        // Delete user
        const deleteResult = await db.delete(users)
          .where(eq(users.id, newUser.id));
        console.log('Delete result:', deleteResult);
    
        // Verify deletion
        const [deletedUser] = await db.select().from(users).where(eq(users.id, newUser.id));
        console.log('User after deletion:', deletedUser || 'User not found');
      } catch (error) {
        console.error('Database error:', error);
      }
    }
    
    main().catch(console.error);
    

    Run the example

    npx ts-node src/index.ts
    

    References

    • Drizzle ORM Documentation
    • Drizzle Kit Documentation
    • OceanBase Documentation
    • TypeScript Documentation

    Previous topic

    Prisma
    Last

    Next topic

    Dapper
    Next
    What is on this page
    Prerequisites
    Procedure
    Step 1: Check the versions of Node.js and npm
    Step 2: Install the required dependencies
    Step 2: Configure the database connection
    Step 3: Obtain the connection information of OceanBase Database
    Step 3: Define the data table model
    Step 4: Create a database connection
    Step 5: CRUD operations example
    Run the example
    References