MySQL with Node.js

后端 未结 9 633
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: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'
    

提交回复
热议问题