我刚刚开始接触Node.js。我来自PHP背景,所以我相当习惯使用MySQL来满足我的所有数据库需求。

我如何使用MySQL与Node.js?


当前回答

在我看来,你应该尝试MySQL Connector/Node.js,这是MySQL的官方Node.js驱动程序。 详见ref-1和ref-2。 我尝试了mysqljs/mysql,这里是可用的,但我没有找到这个库的类,方法,属性的详细文档。

所以我切换到标准的MySQL Connector/Node.js和X DevAPI,因为它是一个异步的基于承诺的客户端库,并提供了良好的文档。 看一下下面的代码片段:

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

其他回答

您还可以尝试一种名为Node.js DB的新方法,该方法旨在为多个数据库引擎提供一个通用框架。它是用c++构建的,因此性能得到了保证。

具体来说,你可以使用它的db-mysql驱动程序来支持Node.js的MySQL。

您可以跳过ORM,构建器等,并使用sqler和sqler-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');
});

KnexJs可以在Node.JS和浏览器中用作SQL查询构建器。 我发现它很容易使用。让我们试试它- 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'
  }
});

你可以这样用

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

or

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

在我看来,你应该尝试MySQL Connector/Node.js,这是MySQL的官方Node.js驱动程序。 详见ref-1和ref-2。 我尝试了mysqljs/mysql,这里是可用的,但我没有找到这个库的类,方法,属性的详细文档。

所以我切换到标准的MySQL Connector/Node.js和X DevAPI,因为它是一个异步的基于承诺的客户端库,并提供了良好的文档。 看一下下面的代码片段:

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

node-mysql可能是用于MySQL数据库的最好的模块之一,它是积极维护和良好的文档。