Node.js MySQL SUBSTRING()函数
SUBSTRING()函数是 MySQL 中的内置函数,用于获取给定范围(含)之间的输入字符串的子字符串。
句法:
SUBSTRING(input_string, from, length)
参数:它需要三个参数,如下所示:
- input_string :这是将执行子字符串的给定字符串。
- from :子字符串将从该位置获取。
- length :它是子字符串的长度。
返回值:它返回给定起始位置和长度之间的输入字符串的子字符串。如果长度超出字符串,则忽略多余的部分。
模块安装:使用以下命令安装mysql模块:
npm install mysql
数据库:我们的 SQL发布者 带有示例数据的表格预览如下所示:
示例 1:
index.js
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 query
let query = `SELECT SUBSTRING("GeeksforGeeks",
8, 20) AS SUBSTRING_Output`;
db_con.query(query, (err, rows) => {
if(err) throw err;
console.log(rows);
});
});
index.js
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 query
let query = `SELECT SUBSTRING(name, 1, 4)
AS SUBSTRING_Name FROM publishers`;
db_con.query(query, (err, rows) => {
if(err) throw err;
console.log(rows);
});
});
使用以下命令运行index.js文件:
node index.js
输出:
示例 2:
index.js
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 query
let query = `SELECT SUBSTRING(name, 1, 4)
AS SUBSTRING_Name FROM publishers`;
db_con.query(query, (err, rows) => {
if(err) throw err;
console.log(rows);
});
});
使用以下命令运行index.js文件:
node index.js
输出: