简体   繁体   English

如何让node.js和mysql一起工作?

[英]How to make node.js and mysql work together?

Thanks in advance for your help! 在此先感谢您的帮助!

I am making a node/express app and I want to use a mysql database. 我正在制作节点/快递应用程序,我想使用mysql数据库。 But I can't seem to connect to the database. 但我似乎无法连接到数据库。

I know I'm supposed to use the node-mysql module ( https://github.com/felixge/node-mysql ), but I must be doing it wrong. 我知道我应该使用node-mysql模块( https://github.com/felixge/node-mysql ),但我一定做错了。

I'm completely new to this. 我对此完全陌生。 Do I have to create a database and then create a table? 我是否必须创建数据库然后创建表? Is there a way to create a database elsewhere so it doesn't get erased every time I restart the app? 有没有办法在别处创建数据库,以便每次重新启动应用程序时都不会删除它?

Here's my code. 这是我的代码。 Can someone answer the questions above and tell me what I'm doing wrong below? 有人可以回答上面的问题并告诉我下面我做错了什么吗? Thanks! 谢谢!

var express = require('express'),
  routes = require('./routes'),
  user = require('./routes/user'),
  http = require('http'),
  io = require('socket.io'),
  path = require('path');

var app = express();
var server = http.createServer(app);
sio = io.listen(server);

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(require('stylus').middleware(__dirname + '/public'));
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

server.listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});


var mysql      = require('mysql');
var connection = mysql.createConnection({
  user     : 'me',
  password : 'secret',
  host     : 'localhost',
  port     : app.get('port')
});

connection.connect();

connection.query('CREATE TABLE tesTable (integer int, textfield VARCHAR(100), PRIMARY KEY(integer))',
                  function(err, result){
                      if(err) {
                          console.log(err);
                      } else {
                          console.log("Table testTable Created");
                      }
                  });

By the way, in package.json, I listed 顺便说一句,在package.json中,我列出了

"mysql": "2.0.0-rc2" 

as a dependency and did 作为依赖和做

'npm install'

You can just create your tables in the database as you normally do and it will be persistent enough not to be deleted anytime you restart your app. 您可以像往常一样在数据库中创建表格,并且只要您重新启动应用程序,它就会持续存在,不会被删除。 You can connect to your database by using the following code if you want: 如果需要,可以使用以下代码连接到数据库:

    var mysql = require('mysql');

app.use( connection(mysql, {
    host: 'myhost',
    user: 'user_name',
    password: 'password',
    port: 3306,          //port mysql
    database: 'database_name',
    multipleStatements: 'true'  //false by default

}, 'pool'));

req.getConnection(function(err, connection) {
    connection.query("SELECT * FROM `table_name`;",function (error,row){
        if(!error){
                       //do something.....
        }
        else console.log("Error : "+err);
        });
    //do something else...
});

My first suggestion, besides the question about any errors, is that you should try this 除了关于任何错误的问题之外,我的第一个建议是你应该试试这个

var mysql      = require('mysql');
var connection = mysql.createConnection({
  user     : 'me',
  password : 'secret',
  host     : 'localhost',
  port     : your_MySQL_port
});

The port: app.get('port') in your given example returns your http server port, but not the port of your MySQL server. 给定示例中的port: app.get('port')返回您的http服务器端口,但返回MySQL服务器的端口。

Check https://github.com/felixge/node-mysql#connection-options at 'port'. 在'port'检查https://github.com/felixge/node-mysql#connection-options

To get your MySQL port to insert in your_MySQL_port on Linux or Mac OS, just open a terminal an type: 要让您的MySQL端口插入Linux或Mac OS上的your_MySQL_port ,只需打开一个类型的终端:

ps ax | grep mysqld

as result you will see something like --port=1234 in the generated output. 结果,您将在生成的输出中看到类似--port=1234的内容。 In this case 1234 is your_MySQL_port . 在这种情况下, 1234your_MySQL_port

In this exmaple your code should look like: 在这个例子中,您的代码应如下所示:

var mysql      = require('mysql');
var connection = mysql.createConnection({
  user     : 'me',
  password : 'secret',
  host     : 'localhost',
  port     : 1234
});

You might want to read a few tutorials on MySQL in general before jumping into it with Node, but in case you feel adventurous, here's a very brief tutorial on how I'd go about setting up MySQL on my machine. 在使用Node进入MySQL之前,您可能想要阅读一些关于MySQL的教程,但是如果您喜欢冒险,这里有一个非常简短的教程,介绍如何在我的机器上设置MySQL。

I am assuming that you have access to the MySQL shell. 我假设你有权访问MySQL shell。 If you're using a frontend the process may be different. 如果您正在使用前端,则该过程可能会有所不同。

After installing MySQL and configuring an account, you'd want to log into the MySQL shell with the command 安装MySQL并配置帐户后,您需要使用该命令登录MySQL shell

mysql -u me -p

followed by the password for the MySQL user when prompted. 然后在出现提示时显示MySQL用户的密码。

Next, you'll want to create a database. 接下来,您将要创建一个数据库。 You'd do this with the command 你可以用命令执行此操作

create database mydatabase;

then 然后

use mydatabase;

Next you'll want to create a table. 接下来,您将要创建一个表。 Run the CREATE TABLE query in the shell to set up a table. 在shell中运行CREATE TABLE查询以设置表。 You could do this in Node, but then you'd be running the command needlessly every time you started the app. 您可以在Node中执行此操作,但每次启动应用程序时都会不必要地运行该命令。

Now you should be able to connect using node-mysql 现在您应该能够使用node-mysql进行连接

var connection = mysql.createConnection({
  user     : 'me',
  password : 'secret',
  host     : 'localhost',
  database : 'mydatabase',
  port     :  3306 // or whatever your mysql port is
});

I was facing same issue so how i solve it... 我面临同样的问题,所以我如何解决它...

Mysql Part Mysql部分

1-I have already installed wamp and can access to phpmyadmin.
2-Using phpmyadmin i have created a database and a table say it users(please insert 2,3 rows data using insert menu option) look like 
check 

> http://prntscr.com/72gsxc

3-Make sure wamp is running and mysql service is also running. 
4-Click wamp and mouseover MYSQL and then click my.ini and search there port by default it is 3306.

Node Part 节点部分

var pool =  mysql.createPool({
        host     : 'localhost',
        user     : 'root',
        password : '',
        database : 'cricstream_2',
        port     : 3306
    });

    var readTable = 'SELECT * FROM countries';

        pool.getConnection(function(error, connection){ 
          connection.query(readTable, function(err, rows){
            if(err) throw err;
            else { 
                console.log(rows);
            }
          });
         });

Do I have to create a database and then create a table? 我是否必须创建数据库然后创建表?

Yes, you should create the database and the table ahead of time, that is correct. 是的,你应该提前创建数据库和表,这是正确的。

Is there a way to create a database elsewhere so it doesn't get erased every time I restart the app? 有没有办法在别处创建数据库,以便每次重新启动应用程序时都不会删除它?

Yes, you typically install MySQL server on a computer, this installation manages a run of databases, which you can remove/backup/duplicate etc, and create new databases. 是的,您通常在计算机上安装MySQL服务器,此安装管理一系列数据库,您可以删除/备份/复制等,并创建新数据库。 Your NodeJS app would just be making a connection to your MySQL server installation. 您的NodeJS应用程序只是连接到您的MySQL服务器安装。

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

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