Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# GaussDB Node.js Examples

这里包含了 gaussdb-node 的各种使用示例。

## 文件夹结构

### `async-await/` - 现代异步语法示例
使用 async/await 语法的示例。

### `promises/` - 传统 Promise 语法示例
使用 Promise 链式语法的示例。

## 快速开始

安装 gaussdb-node
```bash
npm install gaussdb-node
```

## 环境变量配置

大部分示例会使用环境变量来配置数据库连接:

```bash
export GAUSSUSER=user
export GAUSSPASSWORD=openGauss@123
export GAUSSHOST=localhost
export GAUSSPORT=5432
export GAUSSDATABASE=data
export GAUSSTESTNOSSL=false
```

## 示例类型

### 基础连接
- 最简单的连接和查询示例
- 使用配置对象连接数据库

### 连接池
- 基础连接池使用
- 连接池错误处理
- 手动检出和释放连接

### 查询操作
- 参数化查询防止SQL注入
- 预编译语句使用
- 事务处理

### 高级功能
- 游标查询大结果集
- 流式查询处理

## 运行示例

```bash
# 运行 async/await 示例
cd async-await
node basic-connection.js

# 运行 Promise 示例
cd promises
node basic-connection.js

# 使用环境变量运行
GAUSSUSER=user GAUSSPASSWORD=openGauss@123 GAUSSHOST=localhost node basic-connection.js
```
20 changes: 20 additions & 0 deletions examples/async-await/basic-connection.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Client } from 'gaussdb-node'

const client = new Client()

async function main() {
try {
await client.connect()
console.log('✓ 连接成功')

const res = await client.query('SELECT $1::text as message', ['Hello world!'])
console.log(res.rows[0].message) // Hello world!
} catch (err) {
console.error('✗ 错误:', err.message)
} finally {
await client.end()
console.log('✓ 连接已关闭')
}
}

main()
55 changes: 55 additions & 0 deletions examples/async-await/connection-pool.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { Pool } from 'gaussdb-node'

const pool = new Pool({
user: process.env.GAUSSUSER || 'user',
host: process.env.GAUSSHOST || 'localhost',
database: process.env.GAUSSDATABASE || 'data',
password: process.env.GAUSSPASSWORD || 'openGauss@123',
port: parseInt(process.env.GAUSSPORT) || 5432,
max: 10,
idleTimeoutMillis: 30000,
})

pool.on('error', (err) => {
console.error('✗ 连接池意外错误:', err)
process.exit(-1)
})

async function useConnectionPool() {
try {
// 创建临时表
await pool.query(`
CREATE TEMP TABLE IF NOT EXISTS temp_users (
id INTEGER,
name VARCHAR(100),
email VARCHAR(100),
created_at TIMESTAMP DEFAULT NOW()
)
`)
console.log('✓ 临时表创建成功')

// 插入测试数据
await pool.query(`
INSERT INTO temp_users (id, name, email) VALUES
(1, '张三', 'zhangsan@example.com'),
(2, '李四', 'lisi@example.com'),
(3, '王五', 'wangwu@example.com')
`)
console.log('✓ 测试数据插入成功')

// 查询数据
const userRes = await pool.query('SELECT COUNT(*) as user_count FROM temp_users')
console.log('✓ 临时表用户数量:', userRes.rows[0].user_count)

// 查询当前时间
const timeRes = await pool.query('SELECT NOW() as current_time')
console.log('✓ 当前时间:', timeRes.rows[0].current_time)
} catch (err) {
console.error('✗ 查询失败:', err.message)
} finally {
await pool.end()
console.log('✓ 连接池已关闭')
}
}

useConnectionPool()
25 changes: 25 additions & 0 deletions examples/async-await/connection-with-config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Client } from 'gaussdb-node'

const client = new Client({
user: process.env.GAUSSUSER || 'user',
host: process.env.GAUSSHOST || 'localhost',
database: process.env.GAUSSDATABASE || 'data',
password: process.env.GAUSSPASSWORD || 'openGauss@123',
port: parseInt(process.env.GAUSSPORT) || 5432,
})

async function connectWithConfig() {
try {
await client.connect()
console.log('✓ 连接成功!')

const res = await client.query('SELECT NOW() as current_time')
console.log('当前时间:', res.rows[0].current_time)
} catch (err) {
console.error('✗ 连接失败:', err.message)
} finally {
await client.end()
}
}

connectWithConfig()
63 changes: 63 additions & 0 deletions examples/async-await/cursor-queries.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { Client } from 'gaussdb-node'
import Cursor from 'gaussdb-cursor'

const client = new Client()

async function demonstrateCursorQueries() {
try {
await client.connect()
console.log('创建临时表用于演示...')

// 创建临时表
await client.query(`
CREATE TEMP TABLE large_table (
id INTEGER PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`)
console.log('✓ 临时表创建成功')

// 插入测试数据
console.log('插入测试数据...')
for (let i = 1; i <= 1000; i++) {
await client.query('INSERT INTO large_table (id, name, email) VALUES ($1, $2, $3)', [
i,
`用户${i}`,
`user${i}@example.com`,
])
}
console.log('✓ 插入了 1000 条测试数据')

console.log('创建游标查询大数据集...')
const query = 'SELECT * FROM large_table ORDER BY id'
const cursor = client.query(new Cursor(query))

let totalRows = 0
let batch

// 批量读取数据,每次100行
while ((batch = await cursor.read(100)).length > 0) {
totalRows += batch.length
console.log(`✓ 处理了 ${batch.length} 行,总计 ${totalRows} 行`)

// 处理每一行数据
batch.forEach((row) => {
// 处理每行数据,显示前5行作为示例
if (row.id <= 5) {
console.log(` 行 ${row.id}: ${row.name} - ${row.email}`)
}
})
}

await cursor.close()
console.log(`✓ 游标查询完成,总共处理 ${totalRows} 行`)
} catch (err) {
console.error('✗ 游标查询失败:', err.message)
} finally {
await client.end()
}
}

demonstrateCursorQueries()
30 changes: 30 additions & 0 deletions examples/async-await/error-handling.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Client } from 'gaussdb-node'

const client = new Client()

async function demonstrateErrorHandling() {
try {
await client.connect()

// 执行查询
const res = await client.query('SELECT $1::text as message', ['Hello world!'])
console.log(res.rows[0].message)
} catch (err) {
// 处理连接或查询错误
if (err.code === 'ECONNREFUSED') {
console.error('✗ 无法连接到数据库服务器')
} else if (err.code === '42P01') {
console.error('✗ 表不存在')
} else if (err.code === '28P01') {
console.error('✗ 认证失败')
} else {
console.error('✗ 数据库错误:', err.message)
}
} finally {
// 确保连接被正确关闭
await client.end()
console.log('✓ 连接已关闭')
}
}

demonstrateErrorHandling()
43 changes: 43 additions & 0 deletions examples/async-await/parameterized-queries.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { Client } from 'gaussdb-node'

const client = new Client()

async function demonstrateParameterizedQueries() {
try {
await client.connect()
console.log('创建临时表用于演示...')

// 创建临时表
await client.query(`
CREATE TEMP TABLE users (
id INTEGER PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`)
console.log('✓ 临时表创建成功')

// ✓ 安全的参数化查询
const userId = 123
const userName = "John O'Doe"

const insertQuery = 'INSERT INTO users(id, name, email) VALUES($1, $2, $3) RETURNING *'
const insertValues = [userId, userName, 'john@example.com']

const insertResult = await client.query(insertQuery, insertValues)
console.log('✓ 插入用户:', insertResult.rows[0])

const selectQuery = 'SELECT * FROM users WHERE name = $1'
const selectValues = [userName]

const selectResult = await client.query(selectQuery, selectValues)
console.log('✓ 查询结果:', selectResult.rows)
} catch (err) {
console.error('✗ 查询失败:', err.message)
} finally {
await client.end()
}
}

demonstrateParameterizedQueries()
54 changes: 54 additions & 0 deletions examples/async-await/pool-checkout.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { Pool } from 'gaussdb-node'

const pool = new Pool()

async function demonstratePoolCheckout() {
// 手动检出连接
const client = await pool.connect()

try {
console.log('✓ 获取到连接')
console.log('创建临时表用于演示...')

// 创建临时表
await client.query(`
CREATE TEMP TABLE users (
id INTEGER PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`)
console.log('✓ 临时表创建成功')

// 插入测试数据
await client.query('INSERT INTO users (id, name, email) VALUES ($1, $2, $3)', [1, '张三', 'zhangsan@example.com'])
await client.query('INSERT INTO users (id, name, email) VALUES ($1, $2, $3)', [2, '李四', 'lisi@example.com'])
await client.query('INSERT INTO users (id, name, email) VALUES ($1, $2, $3)', [3, '王五', 'wangwu@example.com'])
console.log('✓ 插入了 3 条测试数据')

// 开始事务
await client.query('BEGIN')

const res1 = await client.query('SELECT COUNT(*) FROM users')
console.log('用户总数:', res1.rows[0].count)

const res2 = await client.query('SELECT NOW() as time')
console.log('查询时间:', res2.rows[0].time)

// 提交事务
await client.query('COMMIT')
console.log('✓ 事务提交成功')
} catch (err) {
console.error('✗ 查询失败:', err)
await client.query('ROLLBACK')
} finally {
// 释放连接回池中
client.release()
console.log('✓ 连接已释放')
}

await pool.end()
}

demonstratePoolCheckout()
Loading