MySQL with Node.js

后端 未结 9 626
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:04

    node-mysql is probably one of the best modules out there used for working with MySQL database which is actively maintained and well documented.

    0 讨论(0)
  • 2020-11-22 12:04

    connect the mysql database by installing a library. here, picked the stable and easy to use node-mysql module.

    npm install mysql@2.0.0-alpha2
    
    var http = require('http'),
       mysql = require('mysql');
    
    var sqlInfo = {
       host: 'localhost',
       user: 'root',
       password: 'urpass',
       database: 'dbname'
    }
    client = mysql.createConnection(sqlInfo);
    
    client.connect();
    

    For NodeJS mysql connecting and querying example

    0 讨论(0)
  • 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/

    0 讨论(0)
  • 2020-11-22 12:07

    You can skip the ORM, builders, etc. and simplify your DB/SQL management using sqler and sqler-mdb.

    -- create this file at: db/mdb/setup/create.database.sql
    CREATE DATABASE IF NOT EXISTS sqlermysql
    
    const conf = {
      "univ": {
        "db": {
          "mdb": {
            "host": "localhost",
            "username":"admin",
            "password": "mysqlpassword"
          }
        }
      },
      "db": {
        "dialects": {
          "mdb": "sqler-mdb"
        },
        "connections": [
          {
            "id": "mdb",
            "name": "mdb",
            "dir": "db/mdb",
            "service": "MySQL",
            "dialect": "mdb",
            "pool": {},
            "driverOptions": {
              "connection": {
                "multipleStatements": true
              }
            }
          }
        ]
      }
    };
    
    // create/initialize manager
    const manager = new Manager(conf);
    await manager.init();
    
    // .sql file path is path to db function
    const result = await manager.db.mdb.setup.create.database();
    
    console.log('Result:', result);
    
    // after we're done using the manager we should close it
    process.on('SIGINT', async function sigintDB() {
      await manager.close();
      console.log('Manager has been closed');
    });
    
    0 讨论(0)
  • 2020-11-22 12:09

    Check out the node.js module list

    • node-mysql — A node.js module implementing the MySQL protocol
    • node-mysql2 — Yet another pure JS async driver. Pipelining, prepared statements.
    • node-mysql-libmysqlclient — MySQL asynchronous bindings based on libmysqlclient

    node-mysql looks simple enough:

    var mysql      = require('mysql');
    var connection = mysql.createConnection({
      host     : 'example.org',
      user     : 'bob',
      password : 'secret',
    });
    
    connection.connect(function(err) {
      // connected! (unless `err` is set)
    });
    

    Queries:

    var post  = {id: 1, title: 'Hello MySQL'};
    var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
      // Neat!
    });
    console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
    
    0 讨论(0)
  • 2020-11-22 12:11

    You can also try out a newer effort known as Node.js DB that aims to provide a common framework for several database engines. It is built with C++ so performance is guaranteed.

    Specifically you could use its db-mysql driver for Node.js MySQL support.

    0 讨论(0)
提交回复
热议问题