📜  Node.js MySQL INSERT()函数

📅  最后修改于: 2022-05-13 01:56:18.965000             🧑  作者: Mango

Node.js MySQL INSERT()函数

INSERT()函数是 MySQL 中的内置函数,用于在删除字符串中的某些字符后将字符串插入到另一个字符串的某个位置。

句法:

INSERT(string_1, position, number_of_characters_to_delete, string_2)

参数:它需要四个参数,如下所示:

  • string_1 :它是作为参数传递的给定主字符串。
  • position : string_2 将插入此位置。
  • number_of_characters_to_delete :它是要从给定位置的 string_1 中删除的字符数。
  • string_2 :它是给定的插入新字符串。

返回值:string_1删除字符然后插入string_2后返回一个新字符串。

模块安装:使用以下命令安装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");
  
    // Here is the query
    let query = 
"SELECT INSERT('GeeksforGeeks', 1, 8, 'All Are ') AS 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");
  
    // Here is the query
    let query = 
"SELECT INSERT(name, 1, 0, 'Publisher - ') AS name FROM publishers";
  
    db_con.query(query, (err, rows) => {
        if(err) throw err;
  
        console.log(rows);
    });
});


使用以下命令运行index.js文件:

node index.js

输出:这里,从位置 1 - 'Geeks' 的 'GeeksforGeeks' 中删除前 8 个字符。然后插入 string_2 – 'All Are Geeks'

示例 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");
  
    // Here is the query
    let query = 
"SELECT INSERT(name, 1, 0, 'Publisher - ') AS name FROM publishers";
  
    db_con.query(query, (err, rows) => {
        if(err) throw err;
  
        console.log(rows);
    });
});

使用以下命令运行index.js文件:

node index.js

输出: