I would like to know what do you think about the following task. I want to write data from JSON object in a database. I would like to separate the SQL logic with the business logic.
I read t'hi strategy has not good performance, when the file js contain a lot of queries.
Which approach is the best practice in your opinion? Can you provide a little example?
var express = require('express'); var app = express(); let mysql = require('mysql') let connection = mysql. createConnection({ host: 'localhost', user: 'root', password: '', database: 'pitch_perfect_db2', multipleStatements: true }) app.
The following are the steps I took. Step 1, install the NPM package called sqlite3 (Read the sqlite3 docs here). sqlite3 helps you to connect to your SQLite database and to run queries. Step 2, In your the JS file where you want to run the SQLs, import/require sqlite3 and fs (No, you don't need to install this one.
Node. js typically supports all database types, regardless of whether they're SQL or NoSQL. Nevertheless, the choice of a database must be made based on the complexity and purposes of your application. In this article, we will take a closer look at SQL and NoSQL databases, as well as at their practical examples.
Node.js can be used in database applications. One of the most popular databases is MySQL.
Your performance question is definitely a 'race your horses' scenario (i.e. test it and see). But in general, if you're going to do this I'd simply export an object with all your named queries like so:
module.exports = {
getAllUsers: "SELECT username, email, displayName FROM users;",
/* other queries */
}
Your calling code can then just require that file and get what it needs:
const queries = require('./db/queries');
queries.getAllUsers // <-- this is now that string
Performance should be about as good as it gets, since your require cache will ensure the file is only read once, and a key-based lookup in JS is pretty quick, even with a thousand or two entries.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With