问题
I am new to AWS and Node js. I want to query a MySQL server in a private ec2 instance in a testing project which I am building using Node js. How should I go about it? Thanks
EDIT: I want to access it through my local computer. The way I came up with was:
Start a terminal from node js - don't know which method would be best
Use the terminal to login into public ec2
connect to private ec2 through public instance
launch the MySQL client through private instance and query it.
I wanted to know if there is a better way to do this. And any advice on how to achieve the same
回答1:
install the package: jm-ez-mysql
npm install jm-ez-mysql --save
use this document url: https://www.npmjs.com/package/jm-ez-mysql
configuration and connection databse database.js file
const My = require('jm-ez-mysql');
// Init DB Connection const connection = My.init({ host: process.env.DBHOST, user: process.env.DBUSER, password: process.env.DBPASSWORD, database: process.env.DATABASE, dateStrings: true, charset: 'utf8mb4', timezone: 'utc', multipleStatements: true, connectTimeout: 100 * 60 * 1000, acquireTimeout: 100 * 60 * 1000, timeout: 100 * 60 * 1000, }); module.exports = { connection, };
In express js project to configuration database
/config
/database.js
/server.js
/.env
const http = require('http');
const app = require('express')();
require('./config/database.js');
const bodyParser = require('body-parser');
const server = http.createServer(app);
server.listen(process.env.ServerPort, '0.0.0.0', () => {
logger.info(`Express server listening on port ${process.env.ServerPort}`);
});
server.js file
const My = require('jm-ez-mysql');
My.first("psu_project", ["id"], "1=1 ").then(function (r) { console.log(r); });
回答2:
Install the package: mysql
npm install -save mysql
Connect MySQL to the server.
Example:
const mysqlConnection = require('mysql').createConnection;
mysqlConnection = mysqlConnection({
host: HOST,
user: DB_USER,
password: DB_PASSWORD,
database: DB_NAME,
});
mysqlConnection.connect();
mysqlConnection.query('SELECT * FROM table_name');
NOTE: query() is an asynchronous function.
来源:https://stackoverflow.com/questions/60504692/access-mysql-server-in-private-ec2-instance-in-nodejs