Broad Network


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

This is part 2 of my series, Using the EMySQL API. In this part of the series, I show you how data definition statements can be used with the EMySQL API. It is simple: type your SQL statement as a string without the ending semicolon, as argument to the query() function. I will use a database called PetStore to explain the use of data definition statements. You should have read the previous part of the series before reaching here, as this is a continuation.

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');
        });

Creating a Table
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.js
More 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

Comments

Become the Writer's Follower
Send the Writer a Message