Home > Software engineering >  How do I use var into query request in javascript?
How do I use var into query request in javascript?

Time:04-15

Hello i'm struggling with using variables that I declared into my jquery request:

var int_example = "42";
int_example = parseInt(id);
var string_example = "42";

const { Client } = require('pg')
const client = new Client({
    user: 'postgres',
    host: 'localhost',
    database: 'postgres',
    password: 'password',
    port: 5432
});

var query = "INSERT INTO data (int,string) VALUES (int_example,string_example);
client.connect()
    .then(() => console.log("Connection a la base de données réussie"))
    .then(() => console.log("Nos commandes:"))
    .catch(e => console.log(e))
    .then(() => client.query(query))

I get this kind of error : "{ error: column "int_example" does not exist" and i'm not sure if the string_example works as well... Seems I can't use type var or i'm doing something wrong please tell me.

Thank you

CodePudding user response:

there are two ways to put variables in JS strings:

  1. concatenation
var query = "INSERT INTO data (int,string) VALUES ("   int_example   ",'"   string_example   "');";
  1. using template literals (recommended)
var query = `INSERT INTO data (int,string) VALUES (${int_example},'${string_example}');`

right now your query does not contain values of int_example and string_example and it's just their names.

CodePudding user response:

Your issues results from your query string. The values of int_example and string_example are not present in your query.

You can fix the issue by either using string interpolation or string concatenation

You solution will be to use one of the below options:

String Interpolation:

var query = `INSERT INTO data (int,string) VALUES (${int_example},${string_example})`;

String Concatenation:

var query = "INSERT INTO data (int,string) VALUES ("   int_example   ","   string_example   ")";

Note: Whenever you create a string from a string and a number/int the result is a string. Number/int is converted into a string when concatenating.

  • Related