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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

i get { error: syntax error at or near "$" with using template literals
make sure you put backticks (`) correctly.
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 ?
link check this.
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
|
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.

1 Comment

i get { error: syntax error at or near "$" with String interpolation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.