Using MySQL from Node.
js
Paul Fodor
CSE316: Fundamentals of Software
Development
Stony Brook University
http://www.cs.stonybrook.edu/~cse316
Node.js MySQL
Node.js can be used in database applications
(https://www.w3schools.com/nodejs/nodejs_mysql.asp)
Install MySQL Driver
npm install mysql
Current issue of Node mysql driver: uses the old password
credentials, so in mysql run:
ALTER USER 'root'@'localhost' IDENTIFIED WITH
mysql_native_password BY 'yourPassword';
FLUSH PRIVILEGES;
2
(c) Pearson Education Inc. and Paul Fodor (CS Stony Brook)
Node.js MySQL
Start by creating a connection to the database and a DB:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "pass4root"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query("CREATE DATABASE mydb", function (err, result) {
if (err) throw err;
console.log("Database created");
});
});
3
(c) Pearson Education Inc. and Paul Fodor (CS Stony Brook)
Node.js MySQL
Create table:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "pass4root",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});
4 });
(c) Pearson Education Inc. and Paul Fodor (CS Stony Brook)
Node.js MySQL
Insert data:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "pass4root",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO customers (name, address) VALUES ('Company Inc', 'Highway 37')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
5 });
(c) Pearson Education Inc. and Paul Fodor (CS Stony Brook)
Node.js MySQL
Query data:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "pass4root",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
6
}); (c) Pearson Education Inc. and Paul Fodor (CS Stony Brook)