提交 ad50e4ad 作者: SiloQIAN

Initial commit

上级 68962fd6
const express = require('express');
const bodyParser = require('body-parser');
const { Pool } = require('dmdb'); // 达梦数据库驱动
const dmdb = require('dmdb'); // 达梦数据库驱动
const app = express();
const port = 3000;
const port = 8829;
// 中间件
app.use(bodyParser.json());
// 达梦数据库连接配置
const pool = new Pool({
host: 'localhost', // 数据库主机地址
port: 5236, // 数据库端口
database: 'DMDB', // 数据库名称
user: 'SYSDBA', // 用户名
password: 'SYSDBA', // 密码
max: 20, // 连接池最大连接数
idleTimeoutMillis: 30000 // 连接最大空闲时间
const dmHost = '10.51.210.4';
const dmPort = 5237;
const dmDatabase = 'ZZ_ZWBH_PLANT_PROTECTION';
const dmUser = 'ZZ_ZWBH_PLANT_PROTECTION';
const dmPassword = 'Pp20210721';
const token = 'ZZ_ZWBH_PLANT_PROTECTION';
const connectString = `dm://${dmUser}:${dmPassword}@${dmHost}:${dmPort}?autoCommit=false&loginEncrypt=false`;
//获取数据库连接
async function getConnection() {
try {
return await dmdb.getConnection(connectString);
} catch (err) {
throw new Error("getConnection error: " + err.message);
}
}
getConnection().then(client => {
client.execute('SELECT 1');
console.log('数据库连接成功');
client.release();
}).catch(err => {
console.error('数据库连接失败:', err);
process.exit(1);
});
// 健康检查端点
......@@ -25,7 +41,16 @@ app.get('/health', (req, res) => {
});
// SQL执行端点
app.post('/execute-sql', async (req, res) => {
app.post('/execute-sql',
(req, res, next) => {
// Bearer Token验证
const token = req.headers['authorization'];
if (!token || token !== `Bearer ${token}`) {
return res.status(401).json({ error: '未授权' });
}
next();
},
async (req, res) => {
const { sql } = req.body;
if (!sql) {
......@@ -43,17 +68,19 @@ app.post('/execute-sql', async (req, res) => {
});
}
console.log(`[${new Date().getTime()}] 执行查询:`, sql);
// 获取数据库连接
const client = await pool.connect();
const client = await getConnection();
try {
// 执行查询
const result = await client.query(sql);
const result = await client.execute(sql);
res.status(200).json({
success: true,
rows: result.rows,
rowCount: result.rowCount,
fields: result.fields
rowCount: result.rowsAffected,
fields: result.name
});
} finally {
// 释放连接回连接池
......@@ -67,7 +94,7 @@ app.post('/execute-sql', async (req, res) => {
detail: process.env.NODE_ENV === 'development' ? err.stack : undefined
});
}
});
});
// 错误处理中间件
app.use((err, req, res, next) => {
......@@ -87,11 +114,9 @@ app.listen(port, () => {
process.on('SIGINT', async () => {
console.log('正在关闭应用...');
try {
await pool.end();
console.log('数据库连接池已关闭');
process.exit(0);
} catch (err) {
console.error('关闭数据库连接池时出错:', err);
console.error('关闭出错:', err);
process.exit(1);
}
});
......
......@@ -7,5 +7,10 @@
},
"author": "silo",
"license": "ISC",
"description": ""
"description": "",
"dependencies": {
"body-parser": "^1.20.3",
"dmdb": "^1.0.33801",
"express": "^4.21.2"
}
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论