Skip to content
Snippets Groups Projects
Commit 19712a5f authored by Brandon Rodriguez's avatar Brandon Rodriguez
Browse files

Create initial MySql helper class

Currently only creates and closes connections.
parent 94b51a13
Branches
No related merge requests found
......@@ -2,8 +2,12 @@
* NodeJS application to connect to MySQL and make database queries.
*/
// System Imports.
// const mysql = require('mysql2');
// User Imports.
import config from './src/config.js';
const config = require('./src/config.js');
const MySql = require('./src/mysql.js');
/**
......@@ -13,7 +17,12 @@ function main() {
console.log('Starting program.');
console.log('');
console.log(config['mysql']);
var debug = true;
// Create MySql helper class.
const mysql = new MySql(config['mysql'], debug);
mysql.open_conn();
mysql.close_conn();
console.log('');
console.log('Terminating program.');
......
......@@ -6,5 +6,7 @@
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"type": "module"
"dependencies": {
"mysql2": "^2.1.0"
}
}
......@@ -5,12 +5,13 @@
var config = {
mysql: {
user: 'root',
password: 'root',
database: 'js_test',
host: '127.0.0.1',
port: '3306'
port: '3306',
database: 'mysql_bot_example',
user: 'root',
password: 'root'
}
}
export default config;
module.exports = config;
/**
* Helper class to handle MySql logic.
*/
// System Imports.
const mysql = require('mysql2');
class MySql {
/**
* Class constructor.
*/
constructor(config, debug) {
if (debug) {
console.log('Starting MySql helper class.');
}
// Save class variables.
this.config = config;
this.debug = debug;
this.connection = null;
}
/**
* Creates and returns a MySql connection object, using provided config values.
*/
open_conn() {
if (this.debug) {
console.log('Creating MySql connection...');
}
// Check if connection is currently open.
if (this.connection != null) {
// Connection currently exists. Close so we can start a new one.
console.log('Connection already exist. Closing old connection first.');
this.close_conn();
}
// Open MySQL connection.
const connection = mysql.createConnection({
host: this.config['host'],
port: this.config['port'],
database: this.config['database'],
user: this.config['user'],
password: this.config['password']
});
console.log('Connection has been created.');
// Save connection to class.
this.connection =connection;
return connection;
}
/**
* Closes current MySql connection.
*/
close_conn() {
if (this.debug) {
console.log('Closing MySql connection...');
}
// Check if connection is currently open.
if (this.connection != null) {
// Connection currently exists. Safe to close.
this.connection.end();
console.log('Connection has been terminated.');
} else {
// Connection does not yet exist. Cannot close.
console.log('There is no connection to close.');
}
}
}
module.exports = MySql;
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment