📜  NodeJS MySQL 创建数据库

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

NodeJS MySQL 创建数据库

介绍:

我们将看到如何在 nodejs 中创建和使用 mysql 数据库。我们将在CREATE DATABASE查询的帮助下完成此操作。

句法:

Create Database Query: CREATE DATABASE gfg_db;

Use Database Query: USE gfg_db

模块:

  • 节点
  • ExpressJs
  • mysql

    设置环境和执行:

  1. 创建项目
    npm init
  2. 安装模块
    npm install express
    npm install mysql
  3. 创建和导出mysql连接对象。
    sqlConnection.js
    const mysql = require("mysql");
      
    let db_con  = mysql.createConnection({
        host: "localhost",
        user: "root",
        password: ''
    });
      
    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 ...`);
    });


    Javascript
    app.get("/createDatabase", (req, res) => {
      
        let databaseName = "gfg_db";
      
        let createQuery = `CREATE DATABASE ${databaseName}`;
      
        // use the query to create a Database.
        database.query(createQuery, (err) => {
            if(err) throw err;
      
            console.log("Database Created Successfully !");
      
            let useQuery = `USE ${databaseName}`;
            database.query(useQuery, (error) => {
                if(error) throw error;
      
                console.log("Using Database");
                  
                return res.send(
    `Created and Using ${databaseName} Database`);
            })
        });
    });


  4. 创建服务器:

    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 ...`);
    });
    
  5. 创建路由以创建数据库并使用它。

    Javascript

    app.get("/createDatabase", (req, res) => {
      
        let databaseName = "gfg_db";
      
        let createQuery = `CREATE DATABASE ${databaseName}`;
      
        // use the query to create a Database.
        database.query(createQuery, (err) => {
            if(err) throw err;
      
            console.log("Database Created Successfully !");
      
            let useQuery = `USE ${databaseName}`;
            database.query(useQuery, (error) => {
                if(error) throw error;
      
                console.log("Using Database");
                  
                return res.send(
    `Created and Using ${databaseName} Database`);
            })
        });
    });
    
  6. 输出:将此链接放入浏览器http://localhost:5000/createDatabase

    Created and Using gfg_db Database