SlideShare una empresa de Scribd logo
1 de 25
Node and SQLLite
SQLite Database with Node
https://www.udemy.com/node-
database/?couponCode=SLIDESHARE
INSTRUCTOR:
LAURENCE SVEKIS
Course instructor : Laurence Svekis
- Over 300 courses in technology and
web applications.
- 20 years of JavaScript web
programming experience
- 500,000+ students across multiple
platforms
- Digital instructor since 2002
READY TO HELP YOU LEARN and
ANSWER ANY questions you may
have.
Windows Terminal
Windows - https://cmder.net/ or use the
command prompt terminal
Launch the Command Prompt - use the Run
window or press the Win + R keys on your
keyboard. Then, type cmd and press Enter.
List current directory of files - dir
Change directory to D drive - cd D:
Change directory down one level - cd..
Change directory to folder by name - cd folder
Make new folder - mkdir folderName
Get help - help
Mac Terminal
Open Terminal by pressing Command+Space or
select terminal in the applications list.
List current directory of files - ls
Change directory to D drive - cd D:
Change directory down one level - cd..
Change directory to folder by name - cd folder
Make new folder - mkdir folderName
Get help - help
Command Line Launch
One node is installed check to see version
installed. Type node -v
Open your editor and create a js file that
contains console.log('Hello World'); save
it as test.js
In the terminal type node test.js and watch
for a result. What gets returned?
NPM - check if its installed npm -v latest
version install npm install npm@latest -g
Create app js file
Create a main app js file to run your node application.
touch app.js
Install setup Node and Express
https://nodejs.org/en/download/
Select the platform and install
Setup of Localhost machine
https://expressjs.com/
In the terminal
node -v
npm install express --save
Npm package.json
Install all the dependencies for your project. Create
a package.json file.
You can also install packages using
Optional flags
--save - installs and adds to the package.json
--save-dev - installs and adds to the package.json
under devDependencies.
Updating packages - check all packages or specific
package.
npm install <package-name>
npm update
npm update <package-name>
Npm install Packages
Default its installed under the current tree. Npm init
to create package.json
Also adds the dependencies to the package.json
file in current folder.
Global installations of the package can be done by
adding the flag -g. Will install package to global
location.
Get global root folder.
npm init
npm install -g <package-name>
npm root -g
Npm uninstall Packages
Default its installed under the current tree.
Also adds the dependencies to the package.json
file in current folder.
Global installations of the package can be done by
adding the flag -g. Will install package to global
location.
Get global root folder.
npm uninstall <package-name>
npm install -g <package-name>
npm root -g
Setup - Local Server
Run app.js and Open Browser to localhost:8080 -
port with http path.
Assign variable to app object.
Open http://localhost:8080/ in your browser.
const express = require('express')
const app = express()
app.get('/', function (req, res) {
res.send('ready')
})
app.listen(8080, function () {
console.log('Server ready')
})
const express = require('express')
const app = express()
app.get('/', function (req, res) {
res.send('ready')
})
const server = app.listen(8080, function () {
console.log('Server ready')
})
node app.js
NodeMon
Nodemon is a utility that will monitor for any
changes in your source and automatically restart
your server. Perfect for development.
npm install -g nodemon
https://nodemon.io/
Run it
nodemon app.js
** make some changes no more node restart
typing ;)
Setup - Local Express Server
Run app.js and Open Browser to localhost:8080 -
port with http path.
Assign variable to app object.
Open http://localhost:8080/ in your browser.
const express = require('express');
const app = express();
const port = 8080;
const server = app.listen(port, function () {
console.log('Server ready')
})
app.get('/', function (req, res) {
res.json({
"status": "ready"
})
})
app.use(function (req, res) {
res.status(404);
});
nodemon app.js
Install SQLlite and MD5 for hash of passwords
https://www.npmjs.com/package/sqlite3
SQLite is a relational database management
system contained in a C library. In contrast to
many other database management systems,
SQLite is not a client–server database engine.
Rather, it is embedded into the end program.
https://www.sqlite.org/about.html
npm install sqlite3
a JavaScript function for hashing messages with
MD5.
https://www.npmjs.com/package/md5
npm install md5
Setup - Database and create Table
Create a new js file to setup a database.
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./db/user.db');
db.run('CREATE TABLE users(id INTEGER PRIMARY KEY
AUTOINCREMENT,first,last,email,password)');
db.close();
touch dbsetup.js
mkdir db
node dbsetup.js
touch insert.js
touch insert.js
Create a new js file to insert to the database.
Add to database new users table.
Catch the errors
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./db/user.db');
let sql = 'INSERT INTO users (first,last,email,password) VALUES
("Laurence", "Svekis", "gappscourses@gmail.com", "password")';
db.run(sql, [], function(err) {
if (err) {
return console.log(err.message);
}
console.log(`Rowid ${this.lastID}`);
});
db.close();
Database as module
Setup the db.js file as the database connection,
useful if you need to change file locations.
Use a module
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('./db/user.db');
module.exports = db;
**** On app.js add
const db = require("./db.js")
touch db.js
Query Database for users
Querying all rows with all() method -
Will output all the contents of the database.
const sqlite3 = require('sqlite3').verbose();
const md5 = require('md5');
const db = new sqlite3.Database('./db/user.db');
module.exports = db;
**** On app.js add
const db = require("./db.js")
const db = require("./db.js")
const query = "select * from users";
db.all(query, function (err, rows) {
if (err) {
throw err;
}
rows.forEach(function (row) {
console.log(row);
});
});
List users in web page
Using express setup a new route for users const express = require('express');
const app = express();
const port = 8080;
const db = require("./db.js")
const server = app.listen(port, function () {
console.log('Server ready')
})
app.get('/users', function (req, res) {
const query = "select * from users";
db.all(query, function (err, rows) {
if (err) {
throw err;
}
res.json({
"data": rows
});
});
})
app.get('/', function (req, res) {
res.json({
"status": "ready"
})
})
app.use(function (req, res) {
res.status(404);
});
List get users by id
In the browser go to the users folder and add an
id value at the end.
app.get("/users/:id", function (req, res) {
const query = "select * from users where id = ?"
const params = [req.params.id]
db.get(query, params, function (err, row) {
if (err) {
throw err;
}
res.json({
"data": row
})
});
});
Create new User
Create the browser side add.html file with a form
for inputs and event listener to send request.
For node setup install of body-parser
https://github.com/expressjs/body-parser body
parsing middleware
<form>
<input type='text' name='first' value='Laurence'>
<input type='text' name='last' value='Svekis'>
<input type='text' name='email' value='example@example.com'>
<input type='text' name='password' value='secret'>
<input type='submit'> </form>
<script>
const myForm = document.querySelector('form');
const inputs = document.querySelectorAll('input');
myForm.addEventListener("submit", function (evt) {
evt.preventDefault();
fetch('/adder', {
method: 'POST'
, body: JSON.stringify({
first: inputs[0].value
, last: inputs[1].value
, email: inputs[2].value
, password: inputs[3].value
, })
, headers: {
"Content-Type": "application/json"
}
}).then(function (response) {
return response.json()
}).then(function (body) {
console.log(body);
});
});
</script>
npm install body-parser
Node get new user data
Submit the form and check for request data from
the body in the console.
const express = require('express');
const app = express();
const port = 8080;
const db = require("./db.js")
const server = app.listen(port, function () {
console.log('Server ready')
})
const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended:true }));
app.post('/adder', function (req, res) {
console.log(req.body);
console.log('req.body.first', req.body['first']);
})
Add new user to database
Update post to insert into database.
You can go to users to list all
http://localhost:8080/users
const express = require('express');
const app = express();
const port = 8080;
const db = require("./db.js")
const server = app.listen(port, function () {
console.log('Server ready')
})
const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended:true }));
app.post('/adder', function (req, res) {
console.log(req.body);
let insert = 'INSERT INTO users(first,last,email,password) VALUES (?,?,?,?)'
db.run(insert, [req.body['first'], req.body['last'], req.body['email'], req.body['password']],
function (err, row) {
if (err) {
throw err;
}
res.json({
"data": this.lastID
})
});
})
app.use(function (req, res) {
res.status(404);
});
Full Source Code app.js
app.get('/', function (req, res) {
res.json({"status": "ready"})
})
app.get('/new', function (req, res) {
res.sendFile(__dirname + '/add.html');
})
app.post('/adder', function (req, res) {
console.log(req.body);
let insert = 'INSERT INTO users(first,last,email,password) VALUES (?,?,?,?)'
db.run(insert, [req.body['first'], req.body['last'], req.body['email'], req.body['password']],
function (err, row) {
if (err) {throw err;}
res.json({"data": this.lastID })
});
})
app.use(function (req, res) {
res.status(404);
});
const express = require('express');
const app = express();
const port = 8080;
const db = require("./db.js")
const server = app.listen(port, function () {console.log('Server ready')})
const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.get('/users', function (req, res) {
const query = "select * from users";
const params = [];
db.all(query, params, function (err, rows) {
if (err) {throw err;}
res.json({"data": rows});
});
})
app.get("/users/:id", function (req, res) {
const query = "select * from users where id = ?"
const params = [req.params.id]
db.get(query, params, function (err, row) {
if (err) {throw err;}
res.json({ "data": row })
});
});
Full Source Code other files
<!-- add.html -->
<form><input type='text' name='first' value='Laurence'><input type='text' name='last'
value='Svekis'><input type='text' name='email' value='example@example.com'><input
type='text' name='password' value='secret'><input type='submit'> </form>
<script>
const myForm = document.querySelector('form');
const inputs = document.querySelectorAll('input');
myForm.addEventListener("submit", function (evt) {
evt.preventDefault();
fetch('/adder', {
method: 'POST'
, body: JSON.stringify({first: inputs[0].value, last: inputs[1].value, email:
inputs[2].value, password: inputs[3].value })
, headers: {"Content-Type": "application/json" }
}).then(function (response) {
return response.json()
}).then(function (body) {
console.log(body);
});
});
</script>
//db.js
const sqlite3 = require('sqlite3').verbose()
const md5 = require('md5')
const db = new sqlite3.Database('./db/user.db');
module.exports = db
//dbsetup.js
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./db/user.db');
db.run('CREATE TABLE users(id INTEGER PRIMARY KEY
AUTOINCREMENT,first,last,email,password)');
db.close();
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./db/user.db');
let sql = 'INSERT INTO users (first,last,email,password) VALUES ("Laurence", "Svekis",
"gappscourses@gmail.com", "password")';
db.run(sql, [], function(err) {
if (err) {
return console.log(err.message);
}
console.log(`Rowid ${this.lastID}`);
});
db.close();
Congratulations on completing the section
Course instructor : Laurence Svekis -
providing online training to over
500,000 students across hundreds of
courses and many platforms.
Find out more about my courses at
http://www.discoveryvip.com/

Más contenido relacionado

La actualidad más candente

Web Performance Tips
Web Performance TipsWeb Performance Tips
Web Performance Tips
Ravi Raj
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 

La actualidad más candente (20)

J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012
 
Java script Advance
Java script   AdvanceJava script   Advance
Java script Advance
 
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
 
1 ppt-ajax with-j_query
1 ppt-ajax with-j_query1 ppt-ajax with-j_query
1 ppt-ajax with-j_query
 
How to make Ajax work for you
How to make Ajax work for youHow to make Ajax work for you
How to make Ajax work for you
 
Web Performance Tips
Web Performance TipsWeb Performance Tips
Web Performance Tips
 
Web designing unit 4
Web designing unit 4Web designing unit 4
Web designing unit 4
 
Why and How to Use Virtual DOM
Why and How to Use Virtual DOMWhy and How to Use Virtual DOM
Why and How to Use Virtual DOM
 
Html5 For Jjugccc2009fall
Html5 For Jjugccc2009fallHtml5 For Jjugccc2009fall
Html5 For Jjugccc2009fall
 
JavaScript Training
JavaScript TrainingJavaScript Training
JavaScript Training
 
Meetup Performance
Meetup PerformanceMeetup Performance
Meetup Performance
 
JavaScript and jQuery Basics
JavaScript and jQuery BasicsJavaScript and jQuery Basics
JavaScript and jQuery Basics
 
jQuery Best Practice
jQuery Best Practice jQuery Best Practice
jQuery Best Practice
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
tut0000021-hevery
tut0000021-heverytut0000021-hevery
tut0000021-hevery
 
GDI Seattle - Intro to JavaScript Class 4
GDI Seattle - Intro to JavaScript Class 4GDI Seattle - Intro to JavaScript Class 4
GDI Seattle - Intro to JavaScript Class 4
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
CTS Conference Web 2.0 Tutorial Part 2
CTS Conference Web 2.0 Tutorial Part 2CTS Conference Web 2.0 Tutorial Part 2
CTS Conference Web 2.0 Tutorial Part 2
 
JavaScript and BOM events
JavaScript and BOM eventsJavaScript and BOM events
JavaScript and BOM events
 
Javascript and DOM
Javascript and DOMJavascript and DOM
Javascript and DOM
 

Similar a Local SQLite Database with Node for beginners

nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
WalaSidhom1
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
Alex Su
 
Node.js basics
Node.js basicsNode.js basics
Node.js basics
Ben Lin
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
Yehuda Katz
 
Step By Step Guide For Buidling Simple Struts App
Step By Step Guide For Buidling Simple Struts AppStep By Step Guide For Buidling Simple Struts App
Step By Step Guide For Buidling Simple Struts App
Syed Shahul
 
IR Journal (itscholar.codegency.co.in).pdf
IR Journal (itscholar.codegency.co.in).pdfIR Journal (itscholar.codegency.co.in).pdf
IR Journal (itscholar.codegency.co.in).pdf
RahulRoy130127
 

Similar a Local SQLite Database with Node for beginners (20)

Introduction to Node js for beginners + game project
Introduction to Node js for beginners + game projectIntroduction to Node js for beginners + game project
Introduction to Node js for beginners + game project
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
 
SenchaCon 2016: Advanced Techniques for Buidling Ext JS Apps with Electron - ...
SenchaCon 2016: Advanced Techniques for Buidling Ext JS Apps with Electron - ...SenchaCon 2016: Advanced Techniques for Buidling Ext JS Apps with Electron - ...
SenchaCon 2016: Advanced Techniques for Buidling Ext JS Apps with Electron - ...
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Node.js in action
Node.js in actionNode.js in action
Node.js in action
 
NodeJs
NodeJsNodeJs
NodeJs
 
Node.js basics
Node.js basicsNode.js basics
Node.js basics
 
Having Fun with Play
Having Fun with PlayHaving Fun with Play
Having Fun with Play
 
Nodejs.meetup
Nodejs.meetupNodejs.meetup
Nodejs.meetup
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
 
May The Nodejs Be With You
May The Nodejs Be With YouMay The Nodejs Be With You
May The Nodejs Be With You
 
Step By Step Guide For Buidling Simple Struts App
Step By Step Guide For Buidling Simple Struts AppStep By Step Guide For Buidling Simple Struts App
Step By Step Guide For Buidling Simple Struts App
 
TO Hack an ASP .NET website?
TO Hack an ASP .NET website?  TO Hack an ASP .NET website?
TO Hack an ASP .NET website?
 
Hack ASP.NET website
Hack ASP.NET websiteHack ASP.NET website
Hack ASP.NET website
 
Introducing Node.js in an Oracle technology environment (including hands-on)
Introducing Node.js in an Oracle technology environment (including hands-on)Introducing Node.js in an Oracle technology environment (including hands-on)
Introducing Node.js in an Oracle technology environment (including hands-on)
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
 
Node js
Node jsNode js
Node js
 
IR Journal (itscholar.codegency.co.in).pdf
IR Journal (itscholar.codegency.co.in).pdfIR Journal (itscholar.codegency.co.in).pdf
IR Journal (itscholar.codegency.co.in).pdf
 

Más de Laurence Svekis ✔

JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2
Laurence Svekis ✔
 
Top 10 Linkedin Tips Guide 2023
Top 10 Linkedin Tips Guide 2023Top 10 Linkedin Tips Guide 2023
Top 10 Linkedin Tips Guide 2023
Laurence Svekis ✔
 
JavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your codeJavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your code
Laurence Svekis ✔
 
Monster JavaScript Course - 50+ projects and applications
Monster JavaScript Course - 50+ projects and applicationsMonster JavaScript Course - 50+ projects and applications
Monster JavaScript Course - 50+ projects and applications
Laurence Svekis ✔
 
JavaScript Core fundamentals - Learn JavaScript Here
JavaScript Core fundamentals - Learn JavaScript HereJavaScript Core fundamentals - Learn JavaScript Here
JavaScript Core fundamentals - Learn JavaScript Here
Laurence Svekis ✔
 

Más de Laurence Svekis ✔ (19)

Quiz JavaScript Objects Learn more about JavaScript
Quiz JavaScript Objects Learn more about JavaScriptQuiz JavaScript Objects Learn more about JavaScript
Quiz JavaScript Objects Learn more about JavaScript
 
JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2
 
JavaScript Lessons 2023
JavaScript Lessons 2023JavaScript Lessons 2023
JavaScript Lessons 2023
 
Top 10 Linkedin Tips Guide 2023
Top 10 Linkedin Tips Guide 2023Top 10 Linkedin Tips Guide 2023
Top 10 Linkedin Tips Guide 2023
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023
 
Code examples javascript ebook
Code examples javascript ebookCode examples javascript ebook
Code examples javascript ebook
 
Brackets code editor guide
Brackets code editor guideBrackets code editor guide
Brackets code editor guide
 
Web hosting get start online
Web hosting get start onlineWeb hosting get start online
Web hosting get start online
 
JavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptJavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScript
 
Web hosting Free Hosting
Web hosting Free HostingWeb hosting Free Hosting
Web hosting Free Hosting
 
Google Apps Script for Beginners- Amazing Things with Code
Google Apps Script for Beginners- Amazing Things with CodeGoogle Apps Script for Beginners- Amazing Things with Code
Google Apps Script for Beginners- Amazing Things with Code
 
JavaScript DOM - Dynamic interactive Code
JavaScript DOM - Dynamic interactive CodeJavaScript DOM - Dynamic interactive Code
JavaScript DOM - Dynamic interactive Code
 
JavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your codeJavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your code
 
Monster JavaScript Course - 50+ projects and applications
Monster JavaScript Course - 50+ projects and applicationsMonster JavaScript Course - 50+ projects and applications
Monster JavaScript Course - 50+ projects and applications
 
JavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScriptJavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScript
 
JavaScript Core fundamentals - Learn JavaScript Here
JavaScript Core fundamentals - Learn JavaScript HereJavaScript Core fundamentals - Learn JavaScript Here
JavaScript Core fundamentals - Learn JavaScript Here
 
Web Development Introduction to jQuery
Web Development Introduction to jQueryWeb Development Introduction to jQuery
Web Development Introduction to jQuery
 
WordPress for Entrepreneurs Management of your own website
WordPress for Entrepreneurs Management of your own websiteWordPress for Entrepreneurs Management of your own website
WordPress for Entrepreneurs Management of your own website
 
Getting to Know Bootstrap for Rapid Web Development
Getting to Know Bootstrap for Rapid Web DevelopmentGetting to Know Bootstrap for Rapid Web Development
Getting to Know Bootstrap for Rapid Web Development
 

Último

Computer science Sql cheat sheet.pdf.pdf
Computer science Sql cheat sheet.pdf.pdfComputer science Sql cheat sheet.pdf.pdf
Computer science Sql cheat sheet.pdf.pdf
SayantanBiswas37
 
Reconciling Conflicting Data Curation Actions: Transparency Through Argument...
Reconciling Conflicting Data Curation Actions:  Transparency Through Argument...Reconciling Conflicting Data Curation Actions:  Transparency Through Argument...
Reconciling Conflicting Data Curation Actions: Transparency Through Argument...
Bertram Ludäscher
 
如何办理英国诺森比亚大学毕业证(NU毕业证书)成绩单原件一模一样
如何办理英国诺森比亚大学毕业证(NU毕业证书)成绩单原件一模一样如何办理英国诺森比亚大学毕业证(NU毕业证书)成绩单原件一模一样
如何办理英国诺森比亚大学毕业证(NU毕业证书)成绩单原件一模一样
wsppdmt
 
Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...
gajnagarg
 
Top profile Call Girls In Hapur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Hapur [ 7014168258 ] Call Me For Genuine Models We ...Top profile Call Girls In Hapur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Hapur [ 7014168258 ] Call Me For Genuine Models We ...
nirzagarg
 
Top profile Call Girls In dimapur [ 7014168258 ] Call Me For Genuine Models W...
Top profile Call Girls In dimapur [ 7014168258 ] Call Me For Genuine Models W...Top profile Call Girls In dimapur [ 7014168258 ] Call Me For Genuine Models W...
Top profile Call Girls In dimapur [ 7014168258 ] Call Me For Genuine Models W...
gajnagarg
 
Top profile Call Girls In Tumkur [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Tumkur [ 7014168258 ] Call Me For Genuine Models We...Top profile Call Girls In Tumkur [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Tumkur [ 7014168258 ] Call Me For Genuine Models We...
nirzagarg
 
In Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi Arabia
In Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi ArabiaIn Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi Arabia
In Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi Arabia
ahmedjiabur940
 
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
HyderabadDolls
 
+97470301568>>weed for sale in qatar ,weed for sale in dubai,weed for sale in...
+97470301568>>weed for sale in qatar ,weed for sale in dubai,weed for sale in...+97470301568>>weed for sale in qatar ,weed for sale in dubai,weed for sale in...
+97470301568>>weed for sale in qatar ,weed for sale in dubai,weed for sale in...
Health
 
Top profile Call Girls In Purnia [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Purnia [ 7014168258 ] Call Me For Genuine Models We...Top profile Call Girls In Purnia [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Purnia [ 7014168258 ] Call Me For Genuine Models We...
nirzagarg
 
Top profile Call Girls In Chandrapur [ 7014168258 ] Call Me For Genuine Model...
Top profile Call Girls In Chandrapur [ 7014168258 ] Call Me For Genuine Model...Top profile Call Girls In Chandrapur [ 7014168258 ] Call Me For Genuine Model...
Top profile Call Girls In Chandrapur [ 7014168258 ] Call Me For Genuine Model...
gajnagarg
 
Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...
Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...
Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...
HyderabadDolls
 

Último (20)

Computer science Sql cheat sheet.pdf.pdf
Computer science Sql cheat sheet.pdf.pdfComputer science Sql cheat sheet.pdf.pdf
Computer science Sql cheat sheet.pdf.pdf
 
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
 
Reconciling Conflicting Data Curation Actions: Transparency Through Argument...
Reconciling Conflicting Data Curation Actions:  Transparency Through Argument...Reconciling Conflicting Data Curation Actions:  Transparency Through Argument...
Reconciling Conflicting Data Curation Actions: Transparency Through Argument...
 
如何办理英国诺森比亚大学毕业证(NU毕业证书)成绩单原件一模一样
如何办理英国诺森比亚大学毕业证(NU毕业证书)成绩单原件一模一样如何办理英国诺森比亚大学毕业证(NU毕业证书)成绩单原件一模一样
如何办理英国诺森比亚大学毕业证(NU毕业证书)成绩单原件一模一样
 
DATA SUMMIT 24 Building Real-Time Pipelines With FLaNK
DATA SUMMIT 24  Building Real-Time Pipelines With FLaNKDATA SUMMIT 24  Building Real-Time Pipelines With FLaNK
DATA SUMMIT 24 Building Real-Time Pipelines With FLaNK
 
Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...
 
Top profile Call Girls In Hapur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Hapur [ 7014168258 ] Call Me For Genuine Models We ...Top profile Call Girls In Hapur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Hapur [ 7014168258 ] Call Me For Genuine Models We ...
 
Top profile Call Girls In dimapur [ 7014168258 ] Call Me For Genuine Models W...
Top profile Call Girls In dimapur [ 7014168258 ] Call Me For Genuine Models W...Top profile Call Girls In dimapur [ 7014168258 ] Call Me For Genuine Models W...
Top profile Call Girls In dimapur [ 7014168258 ] Call Me For Genuine Models W...
 
Charbagh + Female Escorts Service in Lucknow | Starting ₹,5K To @25k with A/C...
Charbagh + Female Escorts Service in Lucknow | Starting ₹,5K To @25k with A/C...Charbagh + Female Escorts Service in Lucknow | Starting ₹,5K To @25k with A/C...
Charbagh + Female Escorts Service in Lucknow | Starting ₹,5K To @25k with A/C...
 
Top profile Call Girls In Tumkur [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Tumkur [ 7014168258 ] Call Me For Genuine Models We...Top profile Call Girls In Tumkur [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Tumkur [ 7014168258 ] Call Me For Genuine Models We...
 
Gulbai Tekra * Cheap Call Girls In Ahmedabad Phone No 8005736733 Elite Escort...
Gulbai Tekra * Cheap Call Girls In Ahmedabad Phone No 8005736733 Elite Escort...Gulbai Tekra * Cheap Call Girls In Ahmedabad Phone No 8005736733 Elite Escort...
Gulbai Tekra * Cheap Call Girls In Ahmedabad Phone No 8005736733 Elite Escort...
 
TrafficWave Generator Will Instantly drive targeted and engaging traffic back...
TrafficWave Generator Will Instantly drive targeted and engaging traffic back...TrafficWave Generator Will Instantly drive targeted and engaging traffic back...
TrafficWave Generator Will Instantly drive targeted and engaging traffic back...
 
In Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi Arabia
In Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi ArabiaIn Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi Arabia
In Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi Arabia
 
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
 
+97470301568>>weed for sale in qatar ,weed for sale in dubai,weed for sale in...
+97470301568>>weed for sale in qatar ,weed for sale in dubai,weed for sale in...+97470301568>>weed for sale in qatar ,weed for sale in dubai,weed for sale in...
+97470301568>>weed for sale in qatar ,weed for sale in dubai,weed for sale in...
 
Aspirational Block Program Block Syaldey District - Almora
Aspirational Block Program Block Syaldey District - AlmoraAspirational Block Program Block Syaldey District - Almora
Aspirational Block Program Block Syaldey District - Almora
 
Top profile Call Girls In Purnia [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Purnia [ 7014168258 ] Call Me For Genuine Models We...Top profile Call Girls In Purnia [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Purnia [ 7014168258 ] Call Me For Genuine Models We...
 
Top profile Call Girls In Chandrapur [ 7014168258 ] Call Me For Genuine Model...
Top profile Call Girls In Chandrapur [ 7014168258 ] Call Me For Genuine Model...Top profile Call Girls In Chandrapur [ 7014168258 ] Call Me For Genuine Model...
Top profile Call Girls In Chandrapur [ 7014168258 ] Call Me For Genuine Model...
 
Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...
Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...
Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...
 
Ranking and Scoring Exercises for Research
Ranking and Scoring Exercises for ResearchRanking and Scoring Exercises for Research
Ranking and Scoring Exercises for Research
 

Local SQLite Database with Node for beginners

  • 1. Node and SQLLite SQLite Database with Node https://www.udemy.com/node- database/?couponCode=SLIDESHARE
  • 2. INSTRUCTOR: LAURENCE SVEKIS Course instructor : Laurence Svekis - Over 300 courses in technology and web applications. - 20 years of JavaScript web programming experience - 500,000+ students across multiple platforms - Digital instructor since 2002 READY TO HELP YOU LEARN and ANSWER ANY questions you may have.
  • 3. Windows Terminal Windows - https://cmder.net/ or use the command prompt terminal Launch the Command Prompt - use the Run window or press the Win + R keys on your keyboard. Then, type cmd and press Enter. List current directory of files - dir Change directory to D drive - cd D: Change directory down one level - cd.. Change directory to folder by name - cd folder Make new folder - mkdir folderName Get help - help
  • 4. Mac Terminal Open Terminal by pressing Command+Space or select terminal in the applications list. List current directory of files - ls Change directory to D drive - cd D: Change directory down one level - cd.. Change directory to folder by name - cd folder Make new folder - mkdir folderName Get help - help
  • 5. Command Line Launch One node is installed check to see version installed. Type node -v Open your editor and create a js file that contains console.log('Hello World'); save it as test.js In the terminal type node test.js and watch for a result. What gets returned? NPM - check if its installed npm -v latest version install npm install npm@latest -g
  • 6. Create app js file Create a main app js file to run your node application. touch app.js
  • 7. Install setup Node and Express https://nodejs.org/en/download/ Select the platform and install Setup of Localhost machine https://expressjs.com/ In the terminal node -v npm install express --save
  • 8. Npm package.json Install all the dependencies for your project. Create a package.json file. You can also install packages using Optional flags --save - installs and adds to the package.json --save-dev - installs and adds to the package.json under devDependencies. Updating packages - check all packages or specific package. npm install <package-name> npm update npm update <package-name>
  • 9. Npm install Packages Default its installed under the current tree. Npm init to create package.json Also adds the dependencies to the package.json file in current folder. Global installations of the package can be done by adding the flag -g. Will install package to global location. Get global root folder. npm init npm install -g <package-name> npm root -g
  • 10. Npm uninstall Packages Default its installed under the current tree. Also adds the dependencies to the package.json file in current folder. Global installations of the package can be done by adding the flag -g. Will install package to global location. Get global root folder. npm uninstall <package-name> npm install -g <package-name> npm root -g
  • 11. Setup - Local Server Run app.js and Open Browser to localhost:8080 - port with http path. Assign variable to app object. Open http://localhost:8080/ in your browser. const express = require('express') const app = express() app.get('/', function (req, res) { res.send('ready') }) app.listen(8080, function () { console.log('Server ready') }) const express = require('express') const app = express() app.get('/', function (req, res) { res.send('ready') }) const server = app.listen(8080, function () { console.log('Server ready') }) node app.js
  • 12. NodeMon Nodemon is a utility that will monitor for any changes in your source and automatically restart your server. Perfect for development. npm install -g nodemon https://nodemon.io/ Run it nodemon app.js ** make some changes no more node restart typing ;)
  • 13. Setup - Local Express Server Run app.js and Open Browser to localhost:8080 - port with http path. Assign variable to app object. Open http://localhost:8080/ in your browser. const express = require('express'); const app = express(); const port = 8080; const server = app.listen(port, function () { console.log('Server ready') }) app.get('/', function (req, res) { res.json({ "status": "ready" }) }) app.use(function (req, res) { res.status(404); }); nodemon app.js
  • 14. Install SQLlite and MD5 for hash of passwords https://www.npmjs.com/package/sqlite3 SQLite is a relational database management system contained in a C library. In contrast to many other database management systems, SQLite is not a client–server database engine. Rather, it is embedded into the end program. https://www.sqlite.org/about.html npm install sqlite3 a JavaScript function for hashing messages with MD5. https://www.npmjs.com/package/md5 npm install md5
  • 15. Setup - Database and create Table Create a new js file to setup a database. const sqlite3 = require('sqlite3').verbose(); let db = new sqlite3.Database('./db/user.db'); db.run('CREATE TABLE users(id INTEGER PRIMARY KEY AUTOINCREMENT,first,last,email,password)'); db.close(); touch dbsetup.js mkdir db node dbsetup.js touch insert.js touch insert.js Create a new js file to insert to the database. Add to database new users table. Catch the errors const sqlite3 = require('sqlite3').verbose(); let db = new sqlite3.Database('./db/user.db'); let sql = 'INSERT INTO users (first,last,email,password) VALUES ("Laurence", "Svekis", "gappscourses@gmail.com", "password")'; db.run(sql, [], function(err) { if (err) { return console.log(err.message); } console.log(`Rowid ${this.lastID}`); }); db.close();
  • 16. Database as module Setup the db.js file as the database connection, useful if you need to change file locations. Use a module const sqlite3 = require('sqlite3').verbose(); const db = new sqlite3.Database('./db/user.db'); module.exports = db; **** On app.js add const db = require("./db.js") touch db.js
  • 17. Query Database for users Querying all rows with all() method - Will output all the contents of the database. const sqlite3 = require('sqlite3').verbose(); const md5 = require('md5'); const db = new sqlite3.Database('./db/user.db'); module.exports = db; **** On app.js add const db = require("./db.js") const db = require("./db.js") const query = "select * from users"; db.all(query, function (err, rows) { if (err) { throw err; } rows.forEach(function (row) { console.log(row); }); });
  • 18. List users in web page Using express setup a new route for users const express = require('express'); const app = express(); const port = 8080; const db = require("./db.js") const server = app.listen(port, function () { console.log('Server ready') }) app.get('/users', function (req, res) { const query = "select * from users"; db.all(query, function (err, rows) { if (err) { throw err; } res.json({ "data": rows }); }); }) app.get('/', function (req, res) { res.json({ "status": "ready" }) }) app.use(function (req, res) { res.status(404); });
  • 19. List get users by id In the browser go to the users folder and add an id value at the end. app.get("/users/:id", function (req, res) { const query = "select * from users where id = ?" const params = [req.params.id] db.get(query, params, function (err, row) { if (err) { throw err; } res.json({ "data": row }) }); });
  • 20. Create new User Create the browser side add.html file with a form for inputs and event listener to send request. For node setup install of body-parser https://github.com/expressjs/body-parser body parsing middleware <form> <input type='text' name='first' value='Laurence'> <input type='text' name='last' value='Svekis'> <input type='text' name='email' value='example@example.com'> <input type='text' name='password' value='secret'> <input type='submit'> </form> <script> const myForm = document.querySelector('form'); const inputs = document.querySelectorAll('input'); myForm.addEventListener("submit", function (evt) { evt.preventDefault(); fetch('/adder', { method: 'POST' , body: JSON.stringify({ first: inputs[0].value , last: inputs[1].value , email: inputs[2].value , password: inputs[3].value , }) , headers: { "Content-Type": "application/json" } }).then(function (response) { return response.json() }).then(function (body) { console.log(body); }); }); </script> npm install body-parser
  • 21. Node get new user data Submit the form and check for request data from the body in the console. const express = require('express'); const app = express(); const port = 8080; const db = require("./db.js") const server = app.listen(port, function () { console.log('Server ready') }) const bodyParser = require("body-parser"); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended:true })); app.post('/adder', function (req, res) { console.log(req.body); console.log('req.body.first', req.body['first']); })
  • 22. Add new user to database Update post to insert into database. You can go to users to list all http://localhost:8080/users const express = require('express'); const app = express(); const port = 8080; const db = require("./db.js") const server = app.listen(port, function () { console.log('Server ready') }) const bodyParser = require("body-parser"); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended:true })); app.post('/adder', function (req, res) { console.log(req.body); let insert = 'INSERT INTO users(first,last,email,password) VALUES (?,?,?,?)' db.run(insert, [req.body['first'], req.body['last'], req.body['email'], req.body['password']], function (err, row) { if (err) { throw err; } res.json({ "data": this.lastID }) }); }) app.use(function (req, res) { res.status(404); });
  • 23. Full Source Code app.js app.get('/', function (req, res) { res.json({"status": "ready"}) }) app.get('/new', function (req, res) { res.sendFile(__dirname + '/add.html'); }) app.post('/adder', function (req, res) { console.log(req.body); let insert = 'INSERT INTO users(first,last,email,password) VALUES (?,?,?,?)' db.run(insert, [req.body['first'], req.body['last'], req.body['email'], req.body['password']], function (err, row) { if (err) {throw err;} res.json({"data": this.lastID }) }); }) app.use(function (req, res) { res.status(404); }); const express = require('express'); const app = express(); const port = 8080; const db = require("./db.js") const server = app.listen(port, function () {console.log('Server ready')}) const bodyParser = require("body-parser"); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.get('/users', function (req, res) { const query = "select * from users"; const params = []; db.all(query, params, function (err, rows) { if (err) {throw err;} res.json({"data": rows}); }); }) app.get("/users/:id", function (req, res) { const query = "select * from users where id = ?" const params = [req.params.id] db.get(query, params, function (err, row) { if (err) {throw err;} res.json({ "data": row }) }); });
  • 24. Full Source Code other files <!-- add.html --> <form><input type='text' name='first' value='Laurence'><input type='text' name='last' value='Svekis'><input type='text' name='email' value='example@example.com'><input type='text' name='password' value='secret'><input type='submit'> </form> <script> const myForm = document.querySelector('form'); const inputs = document.querySelectorAll('input'); myForm.addEventListener("submit", function (evt) { evt.preventDefault(); fetch('/adder', { method: 'POST' , body: JSON.stringify({first: inputs[0].value, last: inputs[1].value, email: inputs[2].value, password: inputs[3].value }) , headers: {"Content-Type": "application/json" } }).then(function (response) { return response.json() }).then(function (body) { console.log(body); }); }); </script> //db.js const sqlite3 = require('sqlite3').verbose() const md5 = require('md5') const db = new sqlite3.Database('./db/user.db'); module.exports = db //dbsetup.js const sqlite3 = require('sqlite3').verbose(); let db = new sqlite3.Database('./db/user.db'); db.run('CREATE TABLE users(id INTEGER PRIMARY KEY AUTOINCREMENT,first,last,email,password)'); db.close(); const sqlite3 = require('sqlite3').verbose(); let db = new sqlite3.Database('./db/user.db'); let sql = 'INSERT INTO users (first,last,email,password) VALUES ("Laurence", "Svekis", "gappscourses@gmail.com", "password")'; db.run(sql, [], function(err) { if (err) { return console.log(err.message); } console.log(`Rowid ${this.lastID}`); }); db.close();
  • 25. Congratulations on completing the section Course instructor : Laurence Svekis - providing online training to over 500,000 students across hundreds of courses and many platforms. Find out more about my courses at http://www.discoveryvip.com/