MySQL with Node.js

后端 未结 9 632
Happy的楠姐
Happy的楠姐 2020-11-22 11:52

I\'ve just started getting into Node.js. I come from a PHP background, so I\'m fairly used to using MySQL for all my database needs.

How can I use MySQL with Node.js

9条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 12:07

    Here is production code which may help you.

    Package.json

    {
      "name": "node-mysql",
      "version": "0.0.1",
      "dependencies": {
        "express": "^4.10.6",
        "mysql": "^2.5.4"
      }
    }
    

    Here is Server file.

    var express   =    require("express");
    var mysql     =    require('mysql');
    var app       =    express();
    
    var pool      =    mysql.createPool({
        connectionLimit : 100, //important
        host     : 'localhost',
        user     : 'root',
        password : '',
        database : 'address_book',
        debug    :  false
    });
    
    function handle_database(req,res) {
    
        pool.getConnection(function(err,connection){
            if (err) {
              connection.release();
              res.json({"code" : 100, "status" : "Error in connection database"});
              return;
            }   
    
            console.log('connected as id ' + connection.threadId);
    
            connection.query("select * from user",function(err,rows){
                connection.release();
                if(!err) {
                    res.json(rows);
                }           
            });
    
            connection.on('error', function(err) {      
                  res.json({"code" : 100, "status" : "Error in connection database"});
                  return;     
            });
      });
    }
    
    app.get("/",function(req,res){-
            handle_database(req,res);
    });
    
    app.listen(3000);
    

    Reference : https://codeforgeek.com/2015/01/nodejs-mysql-tutorial/

提交回复
热议问题