📜  Node.js MySQL 插入表

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

Node.js MySQL 插入表

NodeJs:用于在服务器端执行 javascript 代码的开源平台。此外,还有一个基于 Chrome 的 V8 JavaScript 引擎的 JavaScript 运行时。它可以从这里下载 Mysql一个使用结构化查询语言 (SQL) 的开源关系数据库管理系统 (RDBMS)。它是在数据库中添加、访问和管理内容的最流行的语言。在这里,我们将使用 Mysql 作为我们节点应用程序的数据库。它可以从这里下载。

在本文中,我们将学习如何使用 Node.js 在 SQL 表中插入行。借助 SQL INSERT Query。

初始化 Node.js 项目:

npm init

安装模块:

npm install express
npm install mysql

文件结构:

MySQL数据库结构:

gfg_db DATABASE.
gfg_table (id INT AUTO_INCREMENT PRIMARY KEY, 
  name VARCHAR(255), address VARCHAR(255)).
sqlConnection.js
// Importing MySQL module
const mysql = require("mysql");
  
// Creating connection
let db_con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "gfg_db"
});
  
// Connect to MySQL server
db_con.connect((err) => {
  if (err) {
    console.log("Database Connection Failed !!!", err);
  } else {
    console.log("connected to Database");
  }
});
  
module.exports = db_con;


index.js
const express = require("express");
const database = require('./sqlConnection');
  
const app = express();
  
app.listen(5000, () => {
  console.log(`Server is up and running on 5000 ...`);
});
  
// Use Route Function from below Examples Here...
  
app.get("/", (req, res) => {
  
    // Call Route Function Here...
});


Javascript
// Function to insert single row values in
// the database
let singleRowInsert = () => {
  
    let query = `INSERT INTO gfg_table 
        (name, address) VALUES (?, ?);`;
  
    // Value to be inserted
    let userName = "Pratik";
    let userAddress = "My Address";
  
    // Creating queries
    db_con.query(query, [userName, 
    userAddress], (err, rows) => {
        if (err) throw err;
        console.log("Row inserted with id = "
            + rows.insertId);
    });
};


Javascript
// Function to insert multiple Row in database
let multipleRowInsert = () => {
  
    // Query to insert multiple rows
    let query = `INSERT INTO gfg_table 
        (name, address) VALUES ?;`;
  
    // Values to be inserted
    let values = [
        ['Amit', 'Yellow Park'],
        ['Rishi', 'Park 38'],
        ['Akash', 'Central st 954'],
        ['Pratik', 'Road 989'],
        ['Mangesh', 'Sideway']
    ];
  
    // Executing the query
    db_con.query(query, [values], (err, rows) => {
        if (err) throw err;
        console.log("All Rows Inserted");
    });
};


每当我们想要进行查询时,我们都会在该文件中导入db_con模块。这将增加我们代码的模块化。

index.js

const express = require("express");
const database = require('./sqlConnection');
  
const app = express();
  
app.listen(5000, () => {
  console.log(`Server is up and running on 5000 ...`);
});
  
// Use Route Function from below Examples Here...
  
app.get("/", (req, res) => {
  
    // Call Route Function Here...
});

例子:

插入单行:下面是插入单行的 Route函数。

Javascript

// Function to insert single row values in
// the database
let singleRowInsert = () => {
  
    let query = `INSERT INTO gfg_table 
        (name, address) VALUES (?, ?);`;
  
    // Value to be inserted
    let userName = "Pratik";
    let userAddress = "My Address";
  
    // Creating queries
    db_con.query(query, [userName, 
    userAddress], (err, rows) => {
        if (err) throw err;
        console.log("Row inserted with id = "
            + rows.insertId);
    });
};

输出:

控制台输出:

Row inserted with id = 1

插入多行:下面是插入多行的 Route函数。

Javascript

// Function to insert multiple Row in database
let multipleRowInsert = () => {
  
    // Query to insert multiple rows
    let query = `INSERT INTO gfg_table 
        (name, address) VALUES ?;`;
  
    // Values to be inserted
    let values = [
        ['Amit', 'Yellow Park'],
        ['Rishi', 'Park 38'],
        ['Akash', 'Central st 954'],
        ['Pratik', 'Road 989'],
        ['Mangesh', 'Sideway']
    ];
  
    // Executing the query
    db_con.query(query, [values], (err, rows) => {
        if (err) throw err;
        console.log("All Rows Inserted");
    });
};

数据库输出:

控制台输出:

All Rows Inserted