0% found this document useful (0 votes)
3 views

database

The document provides a series of JavaScript code snippets for performing various MySQL operations using the 'mysql' library. Operations include connecting to a MySQL server, executing SELECT, INSERT, UPDATE, and DELETE queries, creating databases and tables, and displaying results in the console or via an Express server. Each snippet demonstrates a specific functionality related to database management and manipulation.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

database

The document provides a series of JavaScript code snippets for performing various MySQL operations using the 'mysql' library. Operations include connecting to a MySQL server, executing SELECT, INSERT, UPDATE, and DELETE queries, creating databases and tables, and displaying results in the console or via an Express server. Each snippet demonstrates a specific functionality related to database management and manipulation.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

1.

Connection Test

const mysql = require('mysql');


const con = mysql.createConnection({
host: 'localhost',
user: 'user1',
password: '1234',
});

con.connect((err) => {
if (err) throw err;
console.log('Connected to MySQL Server!');
});

2. select Query
const mysql = require('mysql');
const con = mysql.createConnection({
host: 'localhost',
user: 'user1',
password: '1234',
database: "emp"
});

con.connect((err) => {
if (err) throw err;
console.log('Connected to MySQL Server!');
con.query("SELECT * FROM epersonal", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});

3. create database
var mysql=require('mysql');

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

con.connect(function(err) {
if(err) throw err;
console.log("connected");
//Create a database named "inventory"
con.query("CREATE DATABASE stu1", function(err,result){
if(err) throw err;
else{
console.log("Database Created");
con.query("use stu1");
var sql = "CREATE TABLE student (sno INT, sname
VARCHAR(25), percent INT(3))";
con.query(sql,function(err,result){
if(err) throw err;
console.log("Table Created");
});
}
});
});

4. Slip 5 – Select all records from customer table and delete specified record

var mysql = require('mysql');

var con = mysql.createConnection({


host: "localhost",
user: "user1",
password: "1234",
database: "invoice"
});

con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
var sql = "DELETE FROM customers WHERE cno = 40";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Number of records deleted: " + result.affectedRows);
});

});

5. slip 6- insert multiple records


var mysql=require('mysql');

var con =mysql.createConnection({


host:"localhost",
user:"root",
password:"",
database:"studentsdb"
});

con.connect(function(err){
if(err) throw err;
var records = [
['Arun', 25, 85],
['Jack', 16, 82],
['Priya', 17, 88],
['Amy', 15, 74]
];
con.query("INSERT INTO students (name,rollno,marks) VALUES ?",
[records],function(err,result,fields){
if(err) throw err;

console.log(result);
console.log("Number of rows affected : " + result.affectedRows);
console.log("Number of records affected with warning : " +
result.warningCount);
console.log("Message from Mysql server : " + result.message);
});
});

6. slip7 – display all record from customer table – same as slip5

7. slip13 -update student mark

var mysql = require('mysql');

var con = mysql.createConnection({


host: "localhost",
user: "user1",
password: "1234",
database: "stu"
});

con.connect(function(err) {
if (err) throw err;

var sql = "UPDATE stu SET marks=55 Where rno=10;";


con.query(sql, function (err, result) {
if (err) throw err;
console.log("Number of records updated: " + result.affectedRows);
});

con.query("SELECT * FROM stu", function (err, result, fields) {


if (err) throw err;
console.log(result);
});

});

8. Slip10
SELECT MAX(salary),min(salary),avg(salary) FROM emp,dept WHERE emp.eno =
dept.eno GROUP BY(dname)

var mysql = require('mysql');

var con = mysql.createConnection({


host: "localhost",
user: "user1",
password: "1234",
database: "invoice"
});

con.connect(function(err) {
if (err) throw err;
con.query("SELECT MAX(salary),min(salary),avg(salary) FROM emp,dept WHERE emp.eno =
dept.eno GROUP BY(dname)", function (err, result, fields) {
if (err) throw err;
console.log(result);
});

});

9. slip 16 update emp -same as slip 13

10. slip17- emp detail orderby salary

SELECT * FROM employee ORDER BY salary

var http = require('http');

http.createServer(function (req, res) {


res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<table border=1">');
res.write('<tr>');
res.write('<td>rollNo');
res.write('<td>Name');
res.write('</tr>');
res.write('</table>');
return res.end();
}).listen(8080);

Extract field values

const mysql = require('mysql');


const con = mysql.createConnection({
host: 'localhost',
user: 'user1',
password: '1234',
database: "emp"
});

con.connect((err) => {
if (err) throw err;
console.log('Connected to MySQL Server!');
con.query("SELECT * FROM epersonal", function (err, result, fields) {
if (err) throw err;

Object.keys(result).forEach(function(key) {
var row = result[key];
console.log(row.ename,row.phone)
});
});
});
https://www.youtube.com/watch?v=o9gfAxX_FQE

Using express display output of all records in the browser screen

var express = require('express'),


app = express(),
http = require("http").Server(app).listen(8888)
var mysql = require('mysql');
var formidable=require('formidable');
const path=require('path');
const fs=require('fs');

var con = mysql.createConnection({


host: "localhost",
user: "user1",
password: "1234",
database: "invoice"
});

app.get("/",function(req,res){
res.status(200).sendFile(path.join(__dirname,"simple.html"));
})

app.post('/fapp',function(req,res){

con.connect(function(err){
if(err)throw err;
var sql="select * from employees";
con.query(sql,function(err,result,fields){
//var d=JSON.stringify(result)

res.send(result)
})
})
})

rows.forEach( (row) => {


console.log(`${row.name} lives in ${row.city}`);
});

This gives you the following:


Michaela Lehr lives in Berlin
Michael Wanyoike lives in Nairobi
James Hibbard lives in Munich
Karolina Gawron lives in Wrocław

Creating
You can execute an insert query against a database, like so:
const author = { name: 'Craig Buckler', city: 'Exmouth' };
con.query('INSERT INTO authors SET ?', author, (err, res) => {
if(err) throw err;

console.log('Last insert ID:', res.insertId);


});
Note how we can get the ID of the inserted record using the callback parameter.

Updating
Similarly, when executing an update query, the number of rows affected can be retrieved
using result.affectedRows:
con.query(
'UPDATE authors SET city = ? Where ID = ?',
['Leipzig', 3],
(err, result) => {
if (err) throw err;

console.log(`Changed ${result.changedRows} row(s)`);


}
);

Destroying
The same thing goes for a delete query:
con.query(
'DELETE FROM authors WHERE id = ?', [5], (err, result) => {
if (err) throw err;

console.log(`Deleted ${result.affectedRows} row(s)`);


}
);

You might also like