MySQL con Nodo.js


Acabo de empezar a entrar en el nodo.js. Vengo de un fondo PHP, por lo que estoy bastante acostumbrado a usar MySQL para todas mis necesidades de base de datos.

Cómo puedo usar MySQL con Node.js?

 362
Author: Mark Amery, 2011-04-28

8 answers

Echa un vistazo al nodo .js module list

Node-mysql parece bastante simple:

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'example.org',
  user     : 'bob',
  password : 'secret',
});

connection.connect(function(err) {
  // connected! (unless `err` is set)
});

Consultas:

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'
 421
Author: mak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-02 18:53:36

Node-mysql es probablemente uno de los mejores módulos que se usan para trabajar con bases de datos MySQL que se mantienen activamente y están bien documentadas.

 28
Author: yojimbo87,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-04-28 14:17:19

Dado que este es un hilo antiguo simplemente agregando una actualización:

Para instalar el nodo MySQL.js driver:

Si solo ejecuta npm install mysql, debe estar en el mismo directorio en el que ejecuta su servidor. Yo aconsejaría hacerlo como en uno de los siguientes ejemplos:

Para la instalación global:

npm install -g mysql

Para la instalación local:

1-Agrégalo a tu package.json en las dependencias:

"dependencies": {
    "mysql": "~2.3.2",
     ...

2-ejecutar npm install


Tenga en cuenta que para que las conexiones sucedan, también es necesario ejecutar el servidor mysql (que es independiente del nodo)

Para instalar el servidor MySQL:

Hay un montón de tutoriales por ahí que explican esto, y es un poco dependiente del sistema operativo. Solo tienes que ir a Google y buscar how to install mysql server [Ubuntu|MacOSX|Windows]. Pero en una oración: tienes que ir a http://www.mysql.com/downloads / e instalarlo.

 19
Author: fmsf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-01 11:43:13

Aquí está el código de producción que puede ayudarlo.

Paquete.json

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

Aquí está el archivo del servidor.

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);

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

 10
Author: Shaikh Shahid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-23 14:01:09

También puede probar un esfuerzo más reciente conocido como Nodo .js DB que tiene como objetivo proporcionar un marco común para varios motores de bases de datos. Está construido con C++ por lo que el rendimiento está garantizado.

Específicamente podría usar su controlador db-mysql para el nodo .js MySQL support .

 2
Author: Mariano Iglesias,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-20 23:43:48

KnexJs se puede usar como generador de consultas SQL en ambos nodos.JS y el navegador. Me resulta fácil de usar. Vamos a intentarlo - Knex.js

$ npm install knex --save
# Then add one of the following (adding a --save) flag:
$ npm install pg
$ npm install sqlite3
$ npm install mysql
$ npm install mysql2
$ npm install mariasql
$ npm install strong-oracle
$ npm install oracle
$ npm install mssql


var knex = require('knex')({
  client: 'mysql',
  connection: {
    host : '127.0.0.1',
    user : 'your_database_user',
    password : 'your_database_password',
    database : 'myapp_test'
  }
});

Puedes usarlo así

knex.select('*').from('users')

O

knex('users').where({
  first_name: 'Test',
  last_name:  'User'
}).select('id')
 2
Author: Quy Tang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-13 08:08:19

Conecte la base de datos mysql instalando una biblioteca. aquí, eligió el módulo estable y fácil de usar node-mysql.

npm install [email protected]

var http = require('http'),
   mysql = require('mysql');

var sqlInfo = {
   host: 'localhost',
   user: 'root',
   password: 'urpass',
   database: 'dbname'
}
client = mysql.createConnection(sqlInfo);

client.connect();

Para NodeJS mysql ejemplo de conexión y consulta

 0
Author: Prabin Tp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-04 21:07:47
var express = require('express');
var router = express.Router();

/* GET home page. */

var mysql = require('mysql');
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "****",
    database: "nodejs"
});

con.connect(function(err) {
    if (err) throw err;
    console.log("Connected!");
});
module.exports = con;

Siga el enlace http://datainflow.com/nodejs-mysql-connectivity /

 -1
Author: ujjal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-22 16:36:39