Read Record From Access Database With Javascript

five Means to Query your Relational DB using JavaScript

Michael Bogan

Image used nether license from Shutterstock.com

Our Sample Application

Pre-requisites

Build and Deploy the Hello World App

Fetching Data With SQL

          {          "hostname": "ec2-52-73-247-67.compute-1.amazonaws.com",                      
"port": 5432,

"database": "dfb3aad8c026in",
"username": "clqcouauvejtvw", "password": "1b079cad50f3ff9b48948f15a7fa52123bc6795b875348d66886407a266c0f5b" }
          const { Pool } = require('pg');          const conn = new Pool({ connectionString: process.env.DATABASE_URL });        
          async function listUsers(req, res) {          endeavour {          const db = expect conn.connect()          const result = await db.query('SELECT * FROM users');          const results = { users: (result) ? consequence.rows : zippo};          res.render('pages/alphabetize', results );          db.release();          } grab (err) {          console.error(err);          res.ship("Error " + err);          }          }        
          <h1>Users</h1>          <ul>          <% users.map((user) => { %>          <li><%= user.id %> - <%= user.first_name %> <%= user.last_name %></li>          <% }); %>          </ul>        

MySQL Example

          async function listUsers(req, res) {          endeavour {          const conn = look mysql.createConnection(process.env.DATABASE_URL);          const [rows, fields] = expect conn.execute('SELECT * FROM users');          const results = { 'users': rows };          res.render('pages/alphabetize', results );          await conn.end();          } catch (err) {          console.mistake(err);          res.ship("Error " + err);          }          }        

Knex — Abstracting Away SQL

Installing Knex

Using Knex

          const { Pool } = require('pg');
const conn = new Pool({ connectionString: process.env.DATABASE_URL });
          const db = crave('knex')({
customer: 'pg',
connection: process.env.DATABASE_URL
});
          async function listUsers(req, res) {
try {
const result = wait db.select().from('users').limit(5).offset(5);
const results = { 'users': (upshot) ? effect : nil};
res.render('pages/alphabetize', results );
} take hold of (err) {
console.error(err);
res.send("Error " + err);
}
}

Object Relational Mapping (ORM)

Objection

          grade Annotate extends Model {          static get tableName() {
return 'comments';
}
}
          class User extends Model {          static go tableName() {
return 'users';
}
fullName() {
return `${this.first_name} ${this.last_name}`;
}
static go relationMappings() { return {
comments: {
relation: Model.HasManyRelation,
modelClass: Comment,
join: {
from: 'users.id',
to: 'comments.user_id'
}
}
};
}
}
          async office listUsers(req, res) {          attempt {
const users = await User.query().limit(5);
for (i in users) {
const user = users[i];
user.comments = await User.relatedQuery('comments').for(user.id);
}
const results = { 'users': users }; res.return('pages/index', results );
} catch (err) {
console.fault(err);
res.send("Mistake " + err);
}
}
          <h1>Users</h1>
<ul>
<% users.map((user) => { %>
<li><%= user.id %> - <%= user.fullName() %></li>
<ul>
<% user.comments.map((comment) => { %>
<li><%= comment.body %></li>
<% }); %>
</ul>
<% }); %>
</ul>

The "Northward+1 Selects" Problem

          const users = expect User.query().limit(5);          for (i in users) {
const user = users[i];
user.comments = await User.relatedQuery('comments').for(user.id);
}

Bookshelf

          const { Model } = require('objection');
Model.knex(db);
          const bookshelf = require('bookshelf')(db);        
          const Comment = bookshelf.model('Comment', {
tableName: 'comments'
});
const User = bookshelf.model('User', {
tableName: 'users',
comments() {
// by default, bookshelf infers that the strange key is 'user_id'
return this.hasMany('Comment');
}
});
          async function listUsers(req, res) {
try {
const models = await new User()
.fetchPage({
pageSize: 5,
folio: 1,
withRelated: ['comments']
});
users = []; models.map(g => {
const user = grand.attributes;
const comments = m.related('comments');
user.comments = comments.map(c => c.attributes);
users.push(user);
});
const results = { 'users': users }; res.render('pages/index', results );
} catch (err) {
console.error(err);
res.send("Error " + err);
}
}
          <h1>Users</h1>
<ul>
<% users.map((user) => { %>
<li><%= user.id %> - <%= user.first_name %> <%= user.last_name %></li>
<ul>
<% user.comments.map((comment) => { %>
<li><%= comment.body %></li>
<% }); %>
</ul>
<% }); %>
</ul>

Sequelize

Installing Sequelize

Using Sequelize

          const db = require('knex')({
customer: 'pg',
connection: process.env.DATABASE_URL
});
const bookshelf = require('bookshelf')(db)
          const { Sequelize, DataTypes } = crave('sequelize');
const sequelize = new Sequelize(process.env.DATABASE_URL);
          const User = sequelize.ascertain('User', {
first_name: { blazon: DataTypes.String },
last_name: { blazon: DataTypes.Cord },
email: { type: DataTypes.STRING }
},
{
tableName: 'users',
timestamps: fake
}
);
const Annotate = sequelize.ascertain('Comment', {
body: { type: DataTypes.STRING }
}, {
tableName: 'comments',
timestamps: false
}
);
User.hasMany(Comment, { foreignKey: 'user_id' });
          const models = await new User()          .fetchPage({
pageSize: 5,
page: 1,
withRelated: ['comments']
});
users = []; models.map(chiliad => {
const user = m.attributes;
const comments = g.related('comments');
user.comments = comments.map(c => c.attributes);
users.push(user);
});
          const users = await User.findAll({ include: Comment });        

So Which Option Is Best?

smithfluntence.blogspot.com

Source: https://towardsdatascience.com/5-ways-to-query-your-relational-db-using-javascript-d5499711fc7d

0 Response to "Read Record From Access Database With Javascript"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel