NodeJS MySQL LOCATE()函数
LOCATE()函数是 MySQL 中的一个内置函数,用于在从特定位置搜索时获取文本中模式第一次出现的位置。
注意:不区分大小写。
句法:
LOCATE(pattern, text, starting_position)
参数: LOCATE()函数接受上面提到和下面描述的三个参数。
- 模式:要搜索的模式
- 文本:在此文本模式中将被搜索
- 起始位置(可选):搜索将从该位置开始。默认值为 1。
返回值:当从特定位置搜索时,LOCATE()函数返回文本中模式第一次出现的位置。如果出现问题,它将返回 0。
模块:
- mysql:处理 MySQL 连接和查询
npm install mysql
SQL 发布者表预览:
示例 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);
});
});
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);
});
});
输出:
示例 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);
});
});
输出: