Node.js MySQL LEFT() Function
LEFT() Function is a Builtin function in MySQL which is used to get Prefix of a specific size of Given String.
Syntax:
LEFT(input_string, size_of_prefix)
Parameters: LEFT() function accepts two parameters as mentioned above and described below.
- input_string: We will get prefix of this input string
- size_of_prefix: Number of characters in the prefix
Return Value: LEFT() function returns a string which is a prefix of input_string of specific size.
Modules:
- mysql: To handle MySQL Connection and Queries
npm install mysql
SQL publishers Table Preview:
Example 1: Static Query
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 LEFT(name, 4) AS prefix_name FROM publishers" ; db_con.query(query, (err, rows) => { if (err) throw err; console.log(rows); }); }); |
Output:
Example 2: Dynamic Query
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" ); // notice the ? in below query let query = "SELECT LEFT(salary, ?) AS prefix_salary FROM publishers" ; let sizeOfPrefix = 3; // notice second argument in below function db_con.query(query, sizeOfPrefix, (err, rows) => { if (err) throw err; console.log(rows); }); }); |
Output:
Please Login to comment...