I am having trouble understanding the npm package pg and its "dynamic statements".
I want to be able to generate INSERT INTO statements but I only get syntax error in return
var pg = require('pg');
var connectionString = 'postgres://postgres@localhost/db';
pg.connect(connectionString, function(err, client, done) {
if (err) { return console.error(err); }
var queryConfig = {
text: 'INSERT INTO users($1, $2, $3) VALUES($4, $5, $6);',
values: ['username', 'firstname', 'lastname', 'ab', 'A', 'B']
};
client.query(queryConfig, function (err, result) {
if (err) { return console.error(err); }
done();
});
});
The error I get is:
{ [error: syntax error at or near "$1"]
name: 'error',
length: 84,
severity: 'ERROR',
code: '42601',
detail: undefined,
hint: undefined,
position: '19',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
file: 'scan.l',
line: '1053',
routine: 'scanner_yyerror' }
Can anybody help me to understand what I'm doing wrong?
All messages emitted by the PostgreSQL server are assigned five-character error codes that follow the SQL standard's conventions for "SQLSTATE" codes. Applications that need to know which error condition has occurred should usually test the error code, rather than looking at the textual error message.
Condition names can be written in either upper or lower case. (Note that PL/pgSQL does not recognize warning, as opposed to error, condition names; those are classes 00, 01, and 02.) Table A-1. PostgreSQL Error Codes
PostgreSQL is complaining because you're trying to use the first three placeholders as column names: INSERT INTO users ($1, $2, $3) ... You can think of identifiers like variable names in JavaScript: you can't put a variable name into another variable without some sort of eval chicanery. Similarly, you can't put a column name in a placeholder.
Error Message SQL ERROR: syntax error at or near. Troubleshooting This should generally be the first step to troubleshoot any SQL syntax error in a large query: iteratively comment out blocks of SQL to narrow down where the problem is. TIP: To make this process easier, change the group by clause to use position references
Databases generally don't let you use placeholders for identifiers (table names, column names, ...). PostgreSQL is complaining because you're trying to use the first three placeholders as column names:
INSERT INTO users($1, $2, $3) ...
You can think of identifiers like variable names in JavaScript: you can't put a variable name into another variable without some sort of eval
chicanery. Similarly, you can't put a column name in a placeholder.
You should specify the column names without placeholders:
var queryConfig = {
text: 'INSERT INTO users(username, firstname, lastname) VALUES($1, $2, $3);',
values: ['ab', 'A', 'B']
};
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