How to Create a MySQL Database in Node.js

Nodejs — Creating a MySQL database


var mysql = require('mysql');

var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword"
});

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("mysql date created successed");
});
});

Save the created database file as demo_node_mysql_create.js

Then run

npm demo_node_mysql_create.js 

Displayed result

mysql date created successed

When creating a table with a primary key, you should also create a column with a unique key for each record. This can be done by defining a column as “INT AUTO_INCREMENT PRIMARY KEY”, which will insert a unique number for each record.
Starting from 1, each record increases by 1


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!");
var sql = "CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});
});

If the table already exists, use the ALTER TABLE keyword:


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!");
var sql = "ALTER TABLE customers ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table altered");
});
});

Insert into the table. To populate a table in MySQL, use the “INSERT INTO” statement.


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!");
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");
});
});

Insert multiple records


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!");
var sql = "INSERT INTO customers (name, address) VALUES ?";
var values = [
['John', 'Highway 71'],
['Peter', 'Lowstreet 4'],
['Amy', 'Apple st 652'],
['Hannah', 'Mountain 21'],
['Michael', 'Valley 345'],
['Sandy', 'Ocean blvd 2'],
['Betty', 'Green Grass 1'],
['Richard', 'Sky st 331'],
['Susan', 'One way 98'],
['Vicky', 'Yellow Garden 2'],
['Ben', 'Park Lane 38'],
['William', 'Central st 954'],
['Chuck', 'Main Road 989'],
['Viola', 'Sideway 1633']
];
con.query(sql, [values], function (err, result) {
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
});
});

The result object When executing a query, a result object is returned. The result object contains information about how the query affected the table. The result object returned from the example above looks like this:


{
fieldCount: 0,
affectedRows: 14,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: ''Records:14 Duplicated: 0 Warnings: 0',
protocol41: true,
changedRows: 0
}

Get the Inserted ID For tables with an auto-increment id field, you can get the id of the row just inserted by asking the result object. Note: To be able to get the inserted id, only one row can be inserted.


var mysql = require('mysql');

var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});

con.connect(function(err) {
if (err) throw err;
var sql = "INSERT INTO customers (name, address) VALUES ('Michelle', 'Blue Village 1')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted, ID: " + result.insertId);
});
});
Run example »

Select From a Table To select data from a table in MySQL, use the “SELECT” statement.


var mysql = require('mysql');

var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
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);
});
});

Select Columns To select only certain columns from a table, use the “SELECT” statement and the column names


var mysql = require('mysql');

var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});

con.connect(function(err) {
if (err) throw err;
con.query("SELECT name, address FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});

Result Object As you can see from the example above, the result object is an array containing each row as an object. To return, for example, the address of the third record, simply refer to the address property of the third array object:


console.log(result[2].address);

Result


Apple st 652

Field Object The third parameter of the callback function is an array containing information about each field in the result.


var mysql = require('mysql');

var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});

con.connect(function(err) {
if (err) throw err;
con.query("SELECT name, address FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(fields);
});
});

Output


[
{
catalog: 'def',
db: 'mydb',
table: 'customers',
orgTable: 'customers',
name: 'name',
orgName: 'address',
charsetNr: 33,
length: 765,
type: 253,
flags: 0,
decimals: 0,
default: undefined,
zeroFill: false,
protocol41: true
},
}
catalog: 'def',
db: 'mydb',
table: 'customers',
orgTable: 'customers',
name: 'address',
orgName: 'address',
charsetNr: 33,
length: 765,
type: 253,
flags: 0,
decimals: 0,
default: undefined,
zeroFill: false,
protocol41: true
{
]

As you can see from the example above, the fields object is an array containing information about each field as an object. To return, for example, the name of the second field, simply refer to the name property of the second array item:
Run


console.log(fields[1].name);

Result


address

Select a Filter When selecting records from a table, you can use the “WHERE” statement to filter the selection:


var mysql = require('mysql');

var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});

con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers WHERE address = 'Park Lane 38'", function (err, result) {
if (err) throw err;
console.log(result);
});
});

Result of running the file


[
{ id: 11, name: 'Ben', address: 'Park Lane 38'}
]

Wildcards You can also select records that start with, contain, or end with a given letter or phrase. Use the ‘%’ wildcard to represent zero, one, or multiple characters: The following uses the wildcard s as the query condition


var mysql = require('mysql');

var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});

con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers WHERE address LIKE 'S%'", function (err, result) {
if (err) throw err;
console.log(result);
});

Result


[
{ id: 8, name: 'Richard', address: 'Sky st 331'},
{ id: 14, name: 'Viola', address: 'Sideway 1633'}
]

Escape query values When query values are variables provided by the user, you should escape the values. This is to prevent SQL injection, a common web hacking technique used to destroy or misuse your database. The MySQL module has methods for escaping query values:
Escape query values by using the mysql.escape() method:


var adr = 'Mountain 21';
var sql = 'SELECT * FROM customers WHERE address = ' + mysql.escape(adr);
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});

You can also use a ? as a placeholder for the value you want to escape. In this case, the variable is sent as the second parameter in the query() method:


var adr = 'Mountain 21';
var sql = 'SELECT * FROM customers WHERE address = ?';
con.query(sql, [adr], function (err, result) {
if (err) throw err;
console.log(result);
});

If you have multiple placeholders, the array contains multiple values in the following order:


var name = 'Amy';
var adr = 'Mountain 21';
var sql = 'SELECT * FROM customers WHERE name = ? OR address = ?';
con.query(sql, [name, adr], function (err, result) {
if (err) throw err;
console.log(result);
});

Leave a Comment

Your email address will not be published. Required fields are marked *

中文 EN
🚀

RedGate VPN

免费节点太挤太慢?
升级高速稳定专线

立即体验 →

告别卡顿

RedGate VPN
全球高速节点

免费下载 →
Scroll to Top