Data Definition Statements and EMySQL API
Using the EMySQL API – Part 2
Foreword: In this part of the series, I show you how data definition statements can be used with the EMySQL API.
By: Chrysanthus Date Published: 28 Jul 2016
Introduction
Examples of Data Definition Statements
There are many data definition statements. I will use only the CREATE DATABASE and CREATE TABLE statements here. I will use these statements to create the database, PetStore and its table. You use the other data definition statements in the same way as I use these two: as the query() function first argument. You should try all the code samples of this series.
The query() Function Syntax
The query function syntax is:
con.query(`SQLStr`, callbackFn(){});
where con is the connection object. callbackFn(){} is for handling error and result.
Creating a Database
The following code segment will create a database, if connection has been made:
var crtDBStr = `create database PetStore`;
con.query(crtDBStr, function(err)
{
if (err)
console.log(err);
else
console.log('database created');
});
After creating the database, you can select it with the following code segment:
var db = `PetStore`;
con.selectDB(db, function(err)
{
if (err)
console.log(err);
else
console.log('database selected');
});
After selecting the database, you can go on to create tables. The following code segment creates a table:
var crtTableStr = `CREATE TABLE pet (name VARCHAR(20), owner VARCHAR(20), species VARCHAR(20), sex CHAR(1), birth DATE, death DATE)`;
con.query(crtTableStr, function(err)
{
if (err)
console.log(err);
else
console.log('table created');
});
Now, the next time you want to use this same database, you do not have to create it again. You simply select it.
That is it for this part of the series. In the next part of the series, we do data manipulation
Chrys
Related Links
Free Pure ECMAScript MySQL API for Node.jsMore Related Links
Node Mailsend
EMySQL API
Node.js Web Development Course
Major in Website Design
Low Level Programming - Writing ECMAScript Module
ECMAScript Course
BACK NEXT