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

Databases

OceanBase DatabaseOceanBase AI DatabaseOceanBase Cloud OceanSeekOceanBase 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 ServiceOceanBase DataPilotOceanBase OAgent

Connectors and Middleware

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

Databases

OceanBase DatabaseOceanBase AI DatabaseOceanBase Cloud OceanSeekOceanBase 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 ServiceOceanBase DataPilotOceanBase OAgent
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 Drizzle ORM

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

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: Perform CRUD operations
Run the sample program
References

Applicability

Drizzle ORM is applicable to OceanBase Database in MySQL mode.

Drizzle ORM is a lightweight, type-safe ORM for TypeScript. This topic describes how to use Drizzle ORM to connect to OceanBase Database in MySQL mode.

Prerequisites

  • Node.js 16.0.0 or later is installed.
  • npm or yarn is installed.
  • OceanBase Database is deployed and a MySQL mode tenant is created.

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 a project.
  5. Run a sample program.

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

In the terminal, run the following command 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

In the project root directory, create a .env file 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 OceanBase Database deployment personnel or administrator to obtain the database connection information.

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

Parameter description:

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

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 for the email field.
  emailIdx: index('email_idx').on(table.email),
}));

Create a 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 a src/db/index.ts file:

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: Perform CRUD operations

Create a src/index.ts file:

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 sample program

npx ts-node src/index.ts

References

  • Drizzle ORM official documentation
  • Drizzle Kit documentation
  • OceanBase Database documentation
  • TypeScript documentation

Previous topic

Prisma
Last

Next topic

Dapper
Next
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: Perform CRUD operations
Run the sample program
References