【问题标题】:How connect MySQL to Node.js CRUD如何将 MySQL 连接到 Node.js CRUD
【发布时间】:2018-10-01 04:42:56
【问题描述】:

我一直在使用 mongoDB。如何切换到 MySQL?目前,我不知道在哪里看。我应该使用 MySQL 工作台吗? PGAdmin4?我该怎么做或学习做这个?

【问题讨论】:

    标签: javascript mysql node.js windows


    【解决方案1】:

    试试JavaScript mysql package。它是在 JavaScript 中使用 MySQL 的最流行的包,GitHub 自述文件应该会引导您完成使用它的大部分步骤。

    如果您想要第二个选项,我也有使用 node-mysql 包的经验(这取决于 mysql 包)。它使用起来更简单一些,对我也很有效。

    【讨论】:

      【解决方案2】:

      我在这篇文章中添加了如何在 Nodejs 中使用 MySQL。

      第 1 步:在您的 MySQL 数据库中创建表:

      CREATE TABLE IF NOT EXISTS `employee` (
      `id` int(11) NOT NULL COMMENT 'primary key',
        `employee_name` varchar(255) NOT NULL COMMENT 'employee name',
        `employee_salary` double NOT NULL COMMENT 'employee salary',
        `employee_age` int(11) NOT NULL COMMENT 'employee age'
      );
      

      第 2 步:使用此命令安装所有软件包:

      npm install --save mysql express body-parser 
      

      第三步:在同一目录下创建 app.js 文件

      var http = require("http");
      var express = require('express');
      var app = express();
      var mysql      = require('mysql');
      var bodyParser = require('body-parser');
      
      //start mysql connection
      var connection = mysql.createConnection({
        host     : 'localhost', //mysql database host name
        user     : 'root', //mysql database user name
        password : '', //mysql database password
        database : 'dummy_db' //mysql database name
      });
      
      connection.connect(function(err) {
        if (err) throw err
        console.log('You are now connected...')
      })
      //end mysql connection
      
      //start body-parser configuration
      app.use( bodyParser.json() );       // to support JSON-encoded bodies
      app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
        extended: true
      }));
      //end body-parser configuration
      
      //create app server
      var server = app.listen(3000,  "127.0.0.1", function () {
      
        var host = server.address().address
        var port = server.address().port
      
        console.log("Example app listening at http://%s:%s", host, port)
      
      });
      
      //rest api to get all results
      app.get('/employees', function (req, res) {
         connection.query('select * from employee', function (error, results, fields) {
            if (error) throw error;
            res.end(JSON.stringify(results));
          });
      });
      
      //rest api to get a single employee data
      app.get('/employees/:id', function (req, res) {
         console.log(req);
         connection.query('select * from employee where id=?', [req.params.id], function (error, results, fields) {
            if (error) throw error;
            res.end(JSON.stringify(results));
          });
      });
      
      //rest api to create a new record into mysql database
      app.post('/employees', function (req, res) {
         var postData  = req.body;
         connection.query('INSERT INTO employee SET ?', postData, function (error, results, fields) {
            if (error) throw error;
            res.end(JSON.stringify(results));
          });
      });
      
      //rest api to update record into mysql database
      app.put('/employees', function (req, res) {
         connection.query('UPDATE `employee` SET `employee_name`=?,`employee_salary`=?,`employee_age`=? where `id`=?', [req.body.employee_name,req.body.employee_salary, req.body.employee_age, req.body.id], function (error, results, fields) {
            if (error) throw error;
            res.end(JSON.stringify(results));
          });
      });
      
      //rest api to delete record from mysql database
      app.delete('/employees', function (req, res) {
         console.log(req.body);
         connection.query('DELETE FROM `employee` WHERE `id`=?', [req.body.id], function (error, results, fields) {
            if (error) throw error;
            res.end('Record has been deleted!');
          });
      });
      

      第 4 步:使用此命令启动服务器:

       node app.js
      

      如果您遇到任何问题,请关注此link

      【讨论】:

        猜你喜欢
        • 2020-04-09
        • 1970-01-01
        • 2014-02-12
        • 2019-11-10
        • 2018-05-14
        • 1970-01-01
        • 2020-12-05
        • 2017-08-11
        • 2017-12-07
        相关资源
        最近更新 更多