Node-mysql2: How to execute a wildcard like query?

Created on 23 May 2019  路  2Comments  路  Source: sidorares/node-mysql2

I must be doing something silly, but I cannot seem to get a simple wildcardlike query to work.

At the sql command prompt, the following query works and yields the expected results:

SELECT * FROM test WHERE email like "%gmail.com%" LIMIT 25

Yet when I attempt via pool.execute within the library it does not find any records? No errors either, just no records found.

            const [rows, fields] = await pool.
            execute(`SELECT * FROM test WHERE email like "%?%" LIMIT 25`,
                [search.email]);

For comparison purposes, a similar exact match query such as the following does work as expected; but not the wildcarded like version?

            const [rows, fields] = await pool.
            execute(`SELECT * FROM test WHERE email = ?`,
                [search.email]);

What am I missing please?

TIA!

Most helpful comment

unlike non-PS version it's parsed on the server and full SQL syntax rules apply. SELECT * FROM test WHERE email like "%?%" LIMIT 25 query has zero parameters, "%?%" is not a placeholder but literal string.

Can you try this: execute('SELECT * FROM test WHERE email like ? LIMIT 25', [`%${search.email}%`])

All 2 comments

unlike non-PS version it's parsed on the server and full SQL syntax rules apply. SELECT * FROM test WHERE email like "%?%" LIMIT 25 query has zero parameters, "%?%" is not a placeholder but literal string.

Can you try this: execute('SELECT * FROM test WHERE email like ? LIMIT 25', [`%${search.email}%`])

Yes, of course... that makes sense and works as desired.

Thank you!

Was this page helpful?
0 / 5 - 0 ratings