带有 Node.js 的 MySQL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5818312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 19:41:17  来源:igfitidea点击:

MySQL with Node.js

mysqlnode.js

提问by crawf

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.

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

How can I use MySQL with Node.js?

如何在 Node.js 中使用 MySQL?

回答by mak

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'

回答by yojimbo87

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

node-mysql可能是最好的模块之一,用于处理 MySQL 数据库,该数据库得到积极维护且文档齐全。

回答by fmsf

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. I would advise to do it as in one of the following examples:

如果您只运行npm install mysql,则需要位于运行服务器的同一目录中。我建议按照以下示例之一进行操作:

For global installation:

对于全局安装:

npm install -g mysql

For local installation:

对于本地安装:

1- Add it to your package.jsonin 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]. But in a sentence: you have to go to http://www.mysql.com/downloads/and install it.

有很多教程可以解释这一点,它有点依赖于操作系统。只需去谷歌搜索how to install mysql server [Ubuntu|MacOSX|Windows]。但一句话:你必须去http://www.mysql.com/downloads/并安装它。

回答by Shaikh Shahid

Here is production code which may help you.

这是生产代码,可以帮助您。

Package.json

包.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/

回答by Quy Tang

KnexJs can be used as an SQL query builder in both Node.JS and the browser. I find it easy to use. Let try it - Knex.js

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

You can use it like this

你可以像这样使用它

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

or

或者

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

回答by Lex Soft

Imo, you should try MySQL Connector/Node.js which is the official Node.js driver for MySQL. See ref-1and ref-2for detailed explanation. I have tried mysqljs/mysql which is available here, but I don't find detailed documentation on classes, methods, properties of this library.

Imo,您应该尝试 MySQL Connector/Node.js,它是 MySQL 的官方 Node.js 驱动程序。有关详细说明,请参阅ref-1ref-2。我已经尝试了 mysqljs/mysql,它可以在这里找到,但是我没有找到关于这个库的类、方法、属性的详细文档。

So I switched to the standard MySQL Connector/Node.jswith X DevAPI, since it is an asynchronous Promise-basedclient library and provides good documentation. Take a look at the following code snippet :

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

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

回答by Mariano Iglesias

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

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

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

具体来说,您可以将其 db-mysql 驱动程序用于Node.js MySQL 支持

回答by Prabin Tp

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

通过安装库连接mysql数据库。在这里,选择了稳定且易于使用的 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();

For NodeJS mysql connecting and querying example

NodeJS mysql 连接查询示例