Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs - SQL queries in separate file?

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?

like image 385
MrScf Avatar asked Dec 31 '17 16:12

MrScf


People also ask

How do I write multiple SQL queries in node JS?

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.

How do I run a .SQL file in node JS?

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.

Is Node JS good with SQL?

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.

CAN node JS interact with database?

Node.js can be used in database applications. One of the most popular databases is MySQL.


1 Answers

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.

like image 110
Paul Avatar answered Oct 07 '22 10:10

Paul