0

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

GGH
  • 1
  • 2

2 Answers2

1

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.

Mohammad Salehi
  • 162
  • 1
  • 8
  • i get { error: syntax error at or near "$" with using template literals – GGH Apr 14 '22 at 22:33
  • make sure you put backticks (`) correctly. – Mohammad Salehi Apr 14 '22 at 22:37
  • Oh! Thank you seems that ' is not same as ` that's why it didn't work, but now I have { error: duplicate key value violates unique constraint "commande_pkey" do you have any idea ? – GGH Apr 14 '22 at 22:46
  • [link](https://stackoverflow.com/questions/4448340/postgresql-duplicate-key-violates-unique-constraint) check this. – Mohammad Salehi Apr 14 '22 at 22:48
  • I think it's because i'm trying to INSERT INTO data (int_data) VALUES (${int_example}) but my int_data is a primarey key – GGH Apr 14 '22 at 22:53
  • well yes, primary keys should be unique. so if you for example have a row in your table with int_data = 1 you can't insert any other row with the same number. – Mohammad Salehi Apr 14 '22 at 23:00
0

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.