Home » The right way to Carry out CRUD Operations – JavaScript and SQL Instance

The right way to Carry out CRUD Operations – JavaScript and SQL Instance

by Icecream
0 comment

For probably the most half, interactive web site architectures will contain producing or dishing out information of 1 kind or one other. You can actually use HTML kinds to gather person enter. But the form of internet kind that is described right here will solely take you to this point.

What we actually want is a strategy to reliably retailer and manipulate our information inside the software setting.

In this text, I’m going to indicate you the right way to join a again finish database to your information assortment course of. The plan includes tossing some HTML, JavaScript, and the tiny database engine SQLite right into a bowl, mixing vigorously, and seeing what comes out.

This article comes from my Complete LPI Web Development Essentials Study Guide course. If you would like, you possibly can comply with the video model right here:

As you might already know, the SQL in SQLite stands for structured question language. This signifies that the syntax you will use for interacting with a SQLite database will carefully parallel the way you’d do it with databases like MariaDB, Amazon Aurora, Oracle, or Microsoft’s SQL Server. If you’ve got acquired expertise with any of these, you will be proper at residence right here.

Why are we going to make use of SQLite right here? Because it is a extremely popular selection for the form of work you are more likely to undertake in an online setting.

You’ll must create a brand new listing in your machine together with some recordsdata with JavaScript code. We’ll learn to create, modify, and delete information in a SQLite database.

I may incorporate all these actions right into a single file, in fact, however I feel breaking them out into a number of recordsdata will make it simpler to grasp what is going on on.

Connecting to a Database and Creating a Table

Here’s what the primary file will appear to be:

const sqlite3 = require('sqlite3').verbose();

// Create/connect with the database
const db = new sqlite3.Database('mydatabase.db');

// Create a desk
db.run(`CREATE TABLE IF NOT EXISTS customers (
    id INTEGER PRIMARY KEY,
    identify TEXT,
    age INTEGER
)`);

// Insert information
const insertQuery = `INSERT INTO customers (identify, age) VALUES (?, ?)`;
const identify="Trevor";
const age = 5;
db.run(insertQuery, [name, age], operate (err) {
    if (err) {
        console.error(err.message);
    } else {
        console.log(`Inserted information with id ${this.lastID}`);
    }
});

// Close the database connection
db.shut();

We start by loading the sqlite3 module as sqlite3 after which creating the db variable to symbolize our new database occasion. The database will likely be referred to as mydatabase.db.

const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('mydatabase.db');

If there is not a database utilizing that identify in our native listing, the code will create one, in any other case it will simply connect with the one which’s there already.

Since that is our first run, I’ll create a brand new desk inside the mydatabase.db database. There will likely be three keys in our desk: id, identify, and age.

db.run(`CREATE TABLE IF NOT EXISTS customers (
    id INTEGER PRIMARY KEY,
    identify TEXT,
    age INTEGER
)`);

As you possibly can see, id would be the major key that we’ll use to reference particular person information.

We outlined the info kind of every key: integer, textual content and, once more, integer. This definition is one thing we solely must do as soon as. But we do need to get it proper, as a result of altering it later, after we have already added information, might be tough.

Inserting New Data right into a Table

In this part, we’ll will add a brand new document to the desk utilizing the SQL INSERT command.

const insertQuery = `INSERT INTO customers (identify, age) VALUES (?, ?)`;
const identify="Trevor";
const age = 5;
db.run(insertQuery, [name, age], operate (err) {
    if (err) {
        console.error(err.message);
    } else {
        console.log(`Inserted information with id ${this.lastID}`);
    }
});

You’ll in all probability uncover that official SQL documentation all the time capitalizes key syntax phrases like INSERT and SELECT. That’s a helpful greatest follow, but it surely’s not truly obligatory. As a rule, I’m method too lazy to trouble.

The question itself is templated as insertQuery, with the identify and age particulars added as constants within the traces that comply with.

The db.run methodology, utilizing the insertQuery fixed and people two values (identify and age) as attributes, is then executed. Based on the success or failure of the operation, log messages will likely be generated.

But hold on for a second. What’s with these query marks after declaring insertQuery? And why did we have to break this course of into two elements?

This is definitely an necessary safety follow generally known as an escape variable. With this in place, when the db.run() methodology executes the ready assertion, it will mechanically deal with the escaping of the variable worth, stopping SQL injection.

Lastly, we shut down the connection:

db.shut();

Modifying Data

Now let’s examine how the “modify” code works. Like earlier than, we create a SQLite3 fixed after which connect with our database.

This time, nevertheless, our desk already exists, so we are able to go straight to the “modify” part.

const sqlite3 = require('sqlite3').verbose();

// Create/connect with the database
const db = new sqlite3.Database('mydatabase.db');

// Modify information
const updateQuery = `UPDATE customers SET age = ? WHERE identify = ?`;
const updatedAge = 30;
const updatedName="name2";
db.run(updateQuery, [updatedAge, updatedName], operate (err) {
    if (err) {
        console.error(err.message);
    } else {
        console.log(`Modified ${this.adjustments} row(s)`);
    }
});

// Close the database connection
db.shut();

The sample is analogous. We outline an updateQuery methodology to UPDATE a document that we’ll outline. This operation will change the age worth for an entry whose identify equals Trevor.

You could recall that Trevor’s age was earlier listed as 25. We’re going to replace that to 30. Everything else will work the identical as earlier than, together with closing the connection after we’re finished.

This part of code from the third file will delete a document:

const deleteQuery = `DELETE FROM customers WHERE identify = ?`;
const deletedName="name1";
db.run(deleteQuery, [deletedName], operate (err) {
    if (err) {
        console.error(err.message);
    } else {
        console.log(`Deleted ${this.adjustments} row(s)`);
    }
});

The code above will delete the document the place the identify equals Trevor.

You can run any of these recordsdata utilizing the node  command. But it is best to first just remember to’ve put in the sqlite3 module:

$ npm set up sqlite3

Next I’ll use node to run the primary file (that you may select to name db.js).

$ node db.js
Inserted information with id 1

We’ll see {that a} new document has been efficiently inserted. If you record the listing contents, you will additionally see {that a} new mydatabase.db file has been created.

You can all the time manually log into sqlite3 to see how issues may need modified. I’ll reference the mydatabase.db file so we are able to open it up straight away.

$ sqlite3 mydatabase.db

Typing .tables inside the SQLite interface will record all the prevailing tables on this database. In our case, it will be the customers desk we created.

sqlite> .tables
customers
sqlite>

Now I’ll use the SQL choose command to show a document. Here I’ll use the asterisk to symbolize all information and specify the customers desk.

sqlite> SELECT * FROM customers;
1|Trevor|25
sqlite>

We can see that document 1 containing Trevor who’s 25 years outdated has been created. Great!

Finally, we are able to run the delete code which ought to take away Trevor altogether:

const deleteQuery = `DELETE FROM customers WHERE identify = ?`;
const deletedName="Trevor";
db.run(deleteQuery, [deletedName], operate (err) {
    if (err) {
        console.error(err.message);
    } else {
        console.log(`Deleted ${this.adjustments} row(s)`);
    }
});

I ought to be aware that the db.run and db.shut format I used for these strategies will also be known as Database.run(), and database.shut(). It’s only a matter of desire – or, in my case, laziness. I’m a Linux admin, in any case, and the easiest admins are, in precept, lazy.

Summary

We’ve seen how use JavaScript to hook up with a again finish database, create a brand new desk, after which add, modify, and delete information in that desk. And we appear to have gotten away with it, too!

Now do this by yourself pc. But mess around with the values. Even higher: construct one thing sensible.

This article comes from my Complete LPI Web Development Essentials Study Guide course. And there’s far more know-how goodness out there at bootstrap-it.com

You may also like

Leave a Comment