MENU
Nodejs
Node.js connects to MySQL through the mysql npm package, which exposes a connection object created from a configuration object and a single query() method used for every statement.Install
Install the package with npm:| npm install mysql |
Installs the mysql package into the current Node.js project.
createConnection()
mysql.createConnection() builds a connection object from a configuration object specifying host, user, password, and database. It does not open the connection by itself.| var mysql = require('mysql'); var con = mysql.createConnection({ host: ..., user: ..., password: ..., database: ... }); |
Builds the connection object; the connection is not yet opened.
connect()
con.connect() opens the connection, invoking a callback with an error object (or null on success):| con.connect(function(err) { if (err) throw err; console.log("Connected!"); }); |
Opens the connection; err is non-null if the attempt failed.
query()
Every SQL statement – DDL (see Table Definitions), retrieval (see Data Retrieval), or manipulation (see Data Manipulation) – is run through con.query(), which takes the SQL string and a callback receiving err, result, and fields.Node.js runs JavaScript as the client, outside the server – not to be confused with the JavaScript stored programs MySQL Enterprise Edition can run inside the server as of MySQL 9.0 (see Compound Statements).
ch07-mysql.js:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});