简体   繁体   English

MySQL 与 Node.js

[英]MySQL with Node.js

I've just started getting into Node.js.我刚刚开始接触 Node.js。 I come from a PHP background, so I'm fairly used to using MySQL for all my database needs.我来自 PHP 背景,所以我相当习惯使用 MySQL 来满足我所有的数据库需求。

How can I use MySQL with Node.js?如何将 MySQL 与 Node.js 一起使用?

Check out the node.js module list查看node.js 模块列表

node-mysql looks simple enough: node-mysql 看起来很简单:

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'

node-mysql is probably one of the best modules out there used for working with MySQL database which is actively maintained and well documented. node-mysql可能是目前用于处理 MySQL 数据库的最佳模块之一,该数据库得到积极维护和良好记录。

Since this is an old thread just adding an update:由于这是一个旧线程,因此只需添加更新:

To install the MySQL node.js driver:要安装 MySQL node.js 驱动程序:

If you run just npm install mysql , you need to be in the same directory that your run your server.如果您只运行npm install mysql ,您需要在运行服务器的同一目录中。 I would advise to do it as in one of the following examples:我建议按照以下示例之一进行操作:

For global installation:对于全局安装:

npm install -g mysql

For local installation:对于本地安装:

1- Add it to your package.json in the dependencies: 1-将其添加到您的package.json的依赖项中:

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

2- run npm install 2-运行npm install


Note that for connections to happen you will also need to be running the mysql server (which is node independent)请注意,要进行连接,您还需要运行 mysql 服务器(与节点无关)

To install MySQL server:安装 MySQL 服务器:

There are a bunch of tutorials out there that explain this, and it is a bit dependent on operative system.有很多教程可以解释这一点,而且它有点依赖于操作系统。 Just go to google and search for how to install mysql server [Ubuntu|MacOSX|Windows] .只需 go 到谷歌搜索how to install mysql server [Ubuntu|MacOSX|Windows] But in a sentence: you have to go to http://www.mysql.com/downloads/ and install it.但一句话:你必须 go 到http://www.mysql.com/downloads/并安装它。

Here is production code which may help you.这是可能对您有所帮助的生产代码。

Package.json 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/参考: https://codeforgeek.com/2015/01/nodejs-mysql-tutorial/

KnexJs can be used as an SQL query builder in both Node.JS and the browser. KnexJs 可以在 Node.JS 和浏览器中用作 SQL 查询构建器。 I find it easy to use.我觉得它很容易使用。 Let try it - Knex.js让我们试试 - 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'
  }
});

You can use it like this你可以像这样使用它

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

or或者

knex('users').where({
  first_name: 'Test',
  last_name:  'User'
}).select('id')

Imo, you should try MySQL Connector/Node.js which is the official Node.js driver for MySQL. Imo,您应该尝试 MySQL Connector/Node.js,它是 MySQL 的官方 Node.js 驱动程序。 See ref-1 and ref-2 for detailed explanation.有关详细说明,请参见ref-1ref-2 I have tried mysqljs/mysql which is available here , but I don't find detailed documentation on classes, methods, properties of this library.我已经尝试过 mysqljs/mysql ,可在此处找到,但我没有找到有关该库的类、方法和属性的详细文档。

So I switched to the standard MySQL Connector/Node.js with X DevAPI , since it is an asynchronous Promise-based client library and provides good documentation.所以我切换到带有X DevAPI的标准MySQL Connector/Node.js ,因为它是一个基于 Promise 的异步客户端库并提供了很好的文档。 Take a look at the following code snippet:看看下面的代码片段:

const mysqlx = require('@mysql/xdevapi');
const rows = [];

mysqlx.getSession('mysqlx://localhost:33060')
.then(session => {
    const table = session.getSchema('testSchema').getTable('testTable');

    // The criteria is defined through the expression.
    return table.update().where('name = "bar"').set('age', 50)
        .execute()
        .then(() => {
            return table.select().orderBy('name ASC')
                .execute(row => rows.push(row));
        });
})
.then(() => {
    console.log(rows);
});

You can also try out a newer effort known as Node.js DB that aims to provide a common framework for several database engines.您还可以尝试一种名为Node.js DB的更新项目,该项目旨在为多个数据库引擎提供通用框架。 It is built with C++ so performance is guaranteed.它采用 C++ 构建,因此性能得到保证。

Specifically you could use its db-mysql driver for Node.js MySQL support .具体来说,您可以将其 db-mysql 驱动程序用于Node.js MySQL 支持

connect the mysql database by installing a library.通过安装库连接 mysql 数据库。 here, picked the stable and easy to use node-mysql module.在这里,选择了稳定且易于使用的 node-mysql 模块。

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 NodeJS mysql 连接查询示例

You can skip the ORM, builders, etc. and simplify your DB/SQL management using sqler and sqler-mdb .您可以跳过 ORM、构建器等,并使用sqlersqler-mdb简化您的 DB/SQL 管理。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM