连接到数据库
Toolpad Studio 允许您快速连接到任何数据库。
您可以编写自定义函数来连接到您需要的任何数据库。您可以专注于编写数据库查询,而数据获取和显示由 Toolpad Studio 处理。
连接到 MySQL
自定义函数
在 /resources/functions.ts
中,您可以创建一个自定义函数
import mysql from 'mysql2/promise';
async function createConnection() {
const connection = await mysql.createConnection({
host: process.env.MYSQL_HOST,
port: process.env.MYSQL_PORT,
user: process.env.MYSQL_USERNAME,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DATABASE,
namedPlaceholders: true,
});
return connection;
}
export async function getData(order_id: number) {
const connection = await createConnection();
const query = `SELECT * FROM table WHERE order_id = :emailPattern`;
const [rows] = await connection.execute(query, {
emailPattern: order_id,
});
await connection.end();
return rows;
}
如果您的查询不依赖于参数,您甚至可以使用存储在文件系统中的 .sql
文件,以便您可以保持它们的组织性
import * as fs from 'fs/promises';
export async function getData() {
const query = await fs.readFile('./toolpad/resources/getData.sql', {
encoding: 'utf8',
});
const connection = await createConnection();
const [rows] = await connection.execute(query);
await connection.end();
return rows;
}
请记住,您可以通过这些自定义函数在数据库上运行任何 SQL 查询。
使用 SSH 隧道(可选)
您可以创建 SSH 隧道来连接到数据库,而不是直接连接。您可以稍微修改您的函数来实现这一点
import mysql from 'mysql2/promise';
import SSH2Promise from 'ssh2-promise';
async function createConnection() {
const ssh = new SSH2Promise({
host: process.env.BASTION_HOST,
port: 22, // default port for the SSH protocol
username: process.env.BASTION_USERNAME,
privateKey: process.env.BASTION_SSH_KEY.replace(/\\n/g, '\n'),
});
const tunnel = await ssh.addTunnel({
remoteAddr: process.env.MYSQL_HOST,
remotePort: process.env.MYSQL_PORT,
});
const connection = await mysql.createConnection({
host: 'localhost',
port: tunnel.localPort,
user: process.env.MYSQL_USERNAME,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DATABASE,
namedPlaceholders: true,
});
return connection;
}
您应该在最后使用以下代码关闭隧道
await ssh.close();