Use JS object as values on mySQL query string

Miro :

Im using pool to query mySQL on nodejs. We doing and it is working fine.

let values = [1, 2, 3];
DB.pool.query('SELECT * ROM table_name WHERE col1 = ? AND col2 = ? AND col3 = ?' , values, ( err, rows ) => {
    //Do something
});

As you can notice, the where values are on array and we use ? on the query string to insert those values. The problem with this is, on complex queries, there are alot of value.

Is there a way to use object instead?

Something like:

let values = {col1: 1, col1: 2, col1: 3};

and the query string would be like:

SELECT * ROM table_name WHERE col1 = :col1 AND col2 = :col2 AND col3 = :col3

Any help would be appreciated.

Jon Church :

You might be looking for a query builder like knex or slonik.

You could write your own utility function to help interpolate strings into queries, maybe using the JS Template Literals, but there are packages like the above which already exist to help you do some of this.

Ultimately, the answer is "not really". A SQL query is essentially a string. Either you are going to work with a client/library that builds a query for you (which is what whatever client you're already using is doing, letting you pass in an array of values to get interpolated into the string), or you are going to manually create your strings yourself somehow.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=21350&siteId=1