Skip to content

Commit 9a26315

Browse files
authored
Merge pull request #12 from happy-game/examples
feat(examples): add examples
2 parents 9b01951 + 07e5288 commit 9a26315

22 files changed

+1314
-0
lines changed

examples/README.md

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# GaussDB Node.js Examples
2+
3+
这里包含了 gaussdb-node 的各种使用示例。
4+
5+
## 文件夹结构
6+
7+
### `async-await/` - 现代异步语法示例
8+
使用 async/await 语法的示例。
9+
10+
### `promises/` - 传统 Promise 语法示例
11+
使用 Promise 链式语法的示例。
12+
13+
## 快速开始
14+
15+
安装 gaussdb-node
16+
```bash
17+
npm install gaussdb-node
18+
```
19+
20+
## 环境变量配置
21+
22+
大部分示例会使用环境变量来配置数据库连接:
23+
24+
```bash
25+
export GAUSSUSER=user
26+
export GAUSSPASSWORD=openGauss@123
27+
export GAUSSHOST=localhost
28+
export GAUSSPORT=5432
29+
export GAUSSDATABASE=data
30+
export GAUSSTESTNOSSL=false
31+
```
32+
33+
## 示例类型
34+
35+
### 基础连接
36+
- 最简单的连接和查询示例
37+
- 使用配置对象连接数据库
38+
39+
### 连接池
40+
- 基础连接池使用
41+
- 连接池错误处理
42+
- 手动检出和释放连接
43+
44+
### 查询操作
45+
- 参数化查询防止SQL注入
46+
- 预编译语句使用
47+
- 事务处理
48+
49+
### 高级功能
50+
- 游标查询大结果集
51+
- 流式查询处理
52+
53+
## 运行示例
54+
55+
```bash
56+
# 运行 async/await 示例
57+
cd async-await
58+
node basic-connection.js
59+
60+
# 运行 Promise 示例
61+
cd promises
62+
node basic-connection.js
63+
64+
# 使用环境变量运行
65+
GAUSSUSER=user GAUSSPASSWORD=openGauss@123 GAUSSHOST=localhost node basic-connection.js
66+
```
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { Client } from 'gaussdb-node'
2+
3+
const client = new Client()
4+
5+
async function main() {
6+
try {
7+
await client.connect()
8+
console.log('✓ 连接成功')
9+
10+
const res = await client.query('SELECT $1::text as message', ['Hello world!'])
11+
console.log(res.rows[0].message) // Hello world!
12+
} catch (err) {
13+
console.error('✗ 错误:', err.message)
14+
} finally {
15+
await client.end()
16+
console.log('✓ 连接已关闭')
17+
}
18+
}
19+
20+
main()
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import { Pool } from 'gaussdb-node'
2+
3+
const pool = new Pool({
4+
user: process.env.GAUSSUSER || 'user',
5+
host: process.env.GAUSSHOST || 'localhost',
6+
database: process.env.GAUSSDATABASE || 'data',
7+
password: process.env.GAUSSPASSWORD || 'openGauss@123',
8+
port: parseInt(process.env.GAUSSPORT) || 5432,
9+
max: 10,
10+
idleTimeoutMillis: 30000,
11+
})
12+
13+
pool.on('error', (err) => {
14+
console.error('✗ 连接池意外错误:', err)
15+
process.exit(-1)
16+
})
17+
18+
async function useConnectionPool() {
19+
try {
20+
// 创建临时表
21+
await pool.query(`
22+
CREATE TEMP TABLE IF NOT EXISTS temp_users (
23+
id INTEGER,
24+
name VARCHAR(100),
25+
email VARCHAR(100),
26+
created_at TIMESTAMP DEFAULT NOW()
27+
)
28+
`)
29+
console.log('✓ 临时表创建成功')
30+
31+
// 插入测试数据
32+
await pool.query(`
33+
INSERT INTO temp_users (id, name, email) VALUES
34+
(1, '张三', '[email protected]'),
35+
(2, '李四', '[email protected]'),
36+
(3, '王五', '[email protected]')
37+
`)
38+
console.log('✓ 测试数据插入成功')
39+
40+
// 查询数据
41+
const userRes = await pool.query('SELECT COUNT(*) as user_count FROM temp_users')
42+
console.log('✓ 临时表用户数量:', userRes.rows[0].user_count)
43+
44+
// 查询当前时间
45+
const timeRes = await pool.query('SELECT NOW() as current_time')
46+
console.log('✓ 当前时间:', timeRes.rows[0].current_time)
47+
} catch (err) {
48+
console.error('✗ 查询失败:', err.message)
49+
} finally {
50+
await pool.end()
51+
console.log('✓ 连接池已关闭')
52+
}
53+
}
54+
55+
useConnectionPool()
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { Client } from 'gaussdb-node'
2+
3+
const client = new Client({
4+
user: process.env.GAUSSUSER || 'user',
5+
host: process.env.GAUSSHOST || 'localhost',
6+
database: process.env.GAUSSDATABASE || 'data',
7+
password: process.env.GAUSSPASSWORD || 'openGauss@123',
8+
port: parseInt(process.env.GAUSSPORT) || 5432,
9+
})
10+
11+
async function connectWithConfig() {
12+
try {
13+
await client.connect()
14+
console.log('✓ 连接成功!')
15+
16+
const res = await client.query('SELECT NOW() as current_time')
17+
console.log('当前时间:', res.rows[0].current_time)
18+
} catch (err) {
19+
console.error('✗ 连接失败:', err.message)
20+
} finally {
21+
await client.end()
22+
}
23+
}
24+
25+
connectWithConfig()
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import { Client } from 'gaussdb-node'
2+
import Cursor from 'gaussdb-cursor'
3+
4+
const client = new Client()
5+
6+
async function demonstrateCursorQueries() {
7+
try {
8+
await client.connect()
9+
console.log('创建临时表用于演示...')
10+
11+
// 创建临时表
12+
await client.query(`
13+
CREATE TEMP TABLE large_table (
14+
id INTEGER PRIMARY KEY,
15+
name VARCHAR(100),
16+
email VARCHAR(100),
17+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
18+
)
19+
`)
20+
console.log('✓ 临时表创建成功')
21+
22+
// 插入测试数据
23+
console.log('插入测试数据...')
24+
for (let i = 1; i <= 1000; i++) {
25+
await client.query('INSERT INTO large_table (id, name, email) VALUES ($1, $2, $3)', [
26+
i,
27+
`用户${i}`,
28+
`user${i}@example.com`,
29+
])
30+
}
31+
console.log('✓ 插入了 1000 条测试数据')
32+
33+
console.log('创建游标查询大数据集...')
34+
const query = 'SELECT * FROM large_table ORDER BY id'
35+
const cursor = client.query(new Cursor(query))
36+
37+
let totalRows = 0
38+
let batch
39+
40+
// 批量读取数据,每次100行
41+
while ((batch = await cursor.read(100)).length > 0) {
42+
totalRows += batch.length
43+
console.log(`✓ 处理了 ${batch.length} 行,总计 ${totalRows} 行`)
44+
45+
// 处理每一行数据
46+
batch.forEach((row) => {
47+
// 处理每行数据,显示前5行作为示例
48+
if (row.id <= 5) {
49+
console.log(` 行 ${row.id}: ${row.name} - ${row.email}`)
50+
}
51+
})
52+
}
53+
54+
await cursor.close()
55+
console.log(`✓ 游标查询完成,总共处理 ${totalRows} 行`)
56+
} catch (err) {
57+
console.error('✗ 游标查询失败:', err.message)
58+
} finally {
59+
await client.end()
60+
}
61+
}
62+
63+
demonstrateCursorQueries()
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { Client } from 'gaussdb-node'
2+
3+
const client = new Client()
4+
5+
async function demonstrateErrorHandling() {
6+
try {
7+
await client.connect()
8+
9+
// 执行查询
10+
const res = await client.query('SELECT $1::text as message', ['Hello world!'])
11+
console.log(res.rows[0].message)
12+
} catch (err) {
13+
// 处理连接或查询错误
14+
if (err.code === 'ECONNREFUSED') {
15+
console.error('✗ 无法连接到数据库服务器')
16+
} else if (err.code === '42P01') {
17+
console.error('✗ 表不存在')
18+
} else if (err.code === '28P01') {
19+
console.error('✗ 认证失败')
20+
} else {
21+
console.error('✗ 数据库错误:', err.message)
22+
}
23+
} finally {
24+
// 确保连接被正确关闭
25+
await client.end()
26+
console.log('✓ 连接已关闭')
27+
}
28+
}
29+
30+
demonstrateErrorHandling()
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { Client } from 'gaussdb-node'
2+
3+
const client = new Client()
4+
5+
async function demonstrateParameterizedQueries() {
6+
try {
7+
await client.connect()
8+
console.log('创建临时表用于演示...')
9+
10+
// 创建临时表
11+
await client.query(`
12+
CREATE TEMP TABLE users (
13+
id INTEGER PRIMARY KEY,
14+
name VARCHAR(100),
15+
email VARCHAR(100),
16+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
17+
)
18+
`)
19+
console.log('✓ 临时表创建成功')
20+
21+
// ✓ 安全的参数化查询
22+
const userId = 123
23+
const userName = "John O'Doe"
24+
25+
const insertQuery = 'INSERT INTO users(id, name, email) VALUES($1, $2, $3) RETURNING *'
26+
const insertValues = [userId, userName, '[email protected]']
27+
28+
const insertResult = await client.query(insertQuery, insertValues)
29+
console.log('✓ 插入用户:', insertResult.rows[0])
30+
31+
const selectQuery = 'SELECT * FROM users WHERE name = $1'
32+
const selectValues = [userName]
33+
34+
const selectResult = await client.query(selectQuery, selectValues)
35+
console.log('✓ 查询结果:', selectResult.rows)
36+
} catch (err) {
37+
console.error('✗ 查询失败:', err.message)
38+
} finally {
39+
await client.end()
40+
}
41+
}
42+
43+
demonstrateParameterizedQueries()

examples/async-await/pool-checkout.js

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import { Pool } from 'gaussdb-node'
2+
3+
const pool = new Pool()
4+
5+
async function demonstratePoolCheckout() {
6+
// 手动检出连接
7+
const client = await pool.connect()
8+
9+
try {
10+
console.log('✓ 获取到连接')
11+
console.log('创建临时表用于演示...')
12+
13+
// 创建临时表
14+
await client.query(`
15+
CREATE TEMP TABLE users (
16+
id INTEGER PRIMARY KEY,
17+
name VARCHAR(100),
18+
email VARCHAR(100),
19+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
20+
)
21+
`)
22+
console.log('✓ 临时表创建成功')
23+
24+
// 插入测试数据
25+
await client.query('INSERT INTO users (id, name, email) VALUES ($1, $2, $3)', [1, '张三', '[email protected]'])
26+
await client.query('INSERT INTO users (id, name, email) VALUES ($1, $2, $3)', [2, '李四', '[email protected]'])
27+
await client.query('INSERT INTO users (id, name, email) VALUES ($1, $2, $3)', [3, '王五', '[email protected]'])
28+
console.log('✓ 插入了 3 条测试数据')
29+
30+
// 开始事务
31+
await client.query('BEGIN')
32+
33+
const res1 = await client.query('SELECT COUNT(*) FROM users')
34+
console.log('用户总数:', res1.rows[0].count)
35+
36+
const res2 = await client.query('SELECT NOW() as time')
37+
console.log('查询时间:', res2.rows[0].time)
38+
39+
// 提交事务
40+
await client.query('COMMIT')
41+
console.log('✓ 事务提交成功')
42+
} catch (err) {
43+
console.error('✗ 查询失败:', err)
44+
await client.query('ROLLBACK')
45+
} finally {
46+
// 释放连接回池中
47+
client.release()
48+
console.log('✓ 连接已释放')
49+
}
50+
51+
await pool.end()
52+
}
53+
54+
demonstratePoolCheckout()

0 commit comments

Comments
 (0)