Last active
April 30, 2016 23:16
-
-
Save selfish/0cd7af3cb76da6338ba1af4068c8aced to your computer and use it in GitHub Desktop.
Node.js simple MySQL DB driver
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Require libraries: | |
| const _ = require('lodash'); | |
| const mysql = require('mysql'); | |
| // Load configuration for DB server: | |
| var config = require('./config'); | |
| // Create DB connection object: | |
| var conn = mysql.createConnection(config.db); | |
| // Connect to DB | |
| // Source: https://github.com/felixge/node-mysql#establishing-connections | |
| conn.connect(function (err) { | |
| // In case of connection error, log and crash: | |
| if (err) { | |
| console.error('Error connecting to DB: ' + err.stack); | |
| throw err; | |
| } | |
| // Otherwise log connection success: | |
| console.log('Connected to DB with thread ID: ' + conn.threadId); | |
| }); | |
| /** | |
| * Helper function to query DB. | |
| * | |
| * @param query - string - query text | |
| * @param params [optional] - array - params for query | |
| * @param cb - function - callback(err, rows, fields) | |
| */ | |
| function queryDB(query, params, cb) { | |
| // format query for server, if params is not provided, use empty array: | |
| var sql = mysql.format(query, _.isArray(params) ? params : []); | |
| // Query server. If cb is missing, optional params was not provided, use second argument as cb: | |
| conn.query(sql, _.isFunction(cb) ? cb : params); | |
| } | |
| // Expose query method: | |
| module.exports = { | |
| query: queryDB | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment