Well, it's been a bit since I used Node.js, but I was learning it a few months ago when I made a task management app (Taski) with Electron.
You are first going to need to make sure you have MySQL installed with npm (npm install mysql).
In one of your main server files for Node, you will need to use...
var yourVariableName= require('mysql');
This makes sure MySQL is included.
Obviously you could use something else to power your database, but MySQL is the most common & easiest solution.
JavaScript:
var db = mysql.createConnection({
host: "localhost", // Change if you are connecting to another server
database: "DATABASE-NAME-HERE",
user: "USERNAME-HERE",
password: "PASSWORD-HERE"
});
db.connect(function(error) {
if (error) throw error;
console.log("Server is connected to the database!");
});
This will create a DB variable that is connected to your MySQL database with your credentials.
Or, you could do something like this to actually query the database!
JavaScript:
db.connect(function(error) {
if (error) throw error;
console.log("Server is successfully connected to the database!");
db.query("SELECT game_title FROM arcade_games WHERE game_id = 5", function (sqlerror, sqlresult) {
if (sqlerror) throw sqlerror;
console.log(sqlresult);
});
});
I highly recommend setting up separate functions to handle DB connecting & DB querying.
You will obviously need to do a bit more research on how to effectively validate/sanitize user data with Node / JavaScript, but connecting to a database is easy. It's literally just ...
DBCONNECTIONVARIABLE.query(queryGoesHere, function(errorVariable, resultVariable){
// stuff
});
So, once your protected db variable is created you can easily connect.
Or you can open & close your connection as needed, with a simple function to reconnect to the database & initialize the dbconnectionvariable when its required. Then just run your query. That way you can manage your DB connecting in one place instead of across many files.
🙂