Node.js MySQL LOCATE() Function
LOCATE() Function is a Builtin function in MySQL which is used to get position of first occurrence of a pattern in a text when searched from specific position.
Note: It is Not Case Sensitive.
Syntax:
LOCATE(pattern, text, starting_position)
Parameters: LOCATE() function accepts three parameters as mentioned above and described below.
- pattern: Pattern to be Searched
- text: In this text pattern will be searched
- starting_position (optional): Search will start from this position. default value is 1.
Return Value: LOCATE() function returns position of the first occurrence of a pattern in a text when searched from specific position. If something went wrong it will return 0.
Modules:
- mysql: To handle MySQL Connection and Queries
npm install mysql
SQL publishers Table Preview:
Example 1:
Javascript
const mysql = require( "mysql" ); let db_con = mysql.createConnection({ host: "localhost" , user: "root" , password: "" , database: "gfg_db" , }); db_con.connect((err) => { if (err) { console.log( "Database Connection Failed !!!" , err); return ; } console.log( "We are connected to gfg_db database" ); // here is the query let query = `SELECT LOCATE( 'for' , 'GeeksForGeeks' , 3) AS Position`; db_con.query(query, (err, rows) => { if (err) throw err; console.log(rows); }); }); |
Output:
Example 2:
Javascript
const mysql = require( "mysql" ); let db_con = mysql.createConnection({ host: "localhost" , user: "root" , password: "" , database: "gfg_db" , }); db_con.connect((err) => { if (err) { console.log( "Database Connection Failed !!!" , err); return ; } console.log( "We are connected to gfg_db database" ); // here is the query let query = `SELECT name, LOCATE( 'n' , name) AS Position FROM publishers`; db_con.query(query, (err, rows) => { if (err) throw err; console.log(rows); }); }); |
Output:
Please Login to comment...