Reputation: 528
In the express js application, is it possible to assign the name of the table dynamically?
The code is as follows
let table_name = 'fields'
await connection.query(`INSERT INTO ? (name,description) values ('user','user field')`);
This gives an error in the sql syntax as the query which is executed has the quotes around the table name like this.
INSERT INTO 'fields' (name,description) values ('user','user field');
Upvotes: 0
Views: 644
Reputation: 74605
Table names and column names cannot be parameterized for similar reasons that you can't parameterize a variable name in a programming language; they're part of the fixed structure of a program. If table and column names were allowed to be parameterized then several optimisations that are possible to make when you know the structure of input and output data in advance would no longer be viable
The only thing you can do is construct your SQL in a string, using concatenation, and execute it that way. Take great care when doing so; do not allow a potentially hostile user to supply any values that you concatenate into the string without checking their validity first
Upvotes: 1