魏长东

weichangdong

nodejs 连接mysql

发现nodejs和lua差不多,就是用各种第三方的包。这一点我觉得远远比不上php,多数东西都可以自己搞定,就算用第三方,比如redis memcache,装个扩展,很easy搞定。

nodejs连接mysql主要是装nodejs的mysql的package。

{
  "name": "mysql",
  "description": "A node.js driver for mysql. It is written in JavaScript, does not require compiling, and is 100% MIT licensed.",
  "version": "2.11.1",
  "license": "MIT",
  "author": "Felix Geisendörfer <felix@debuggable.com> (http://debuggable.com/)",
  "contributors": [
    "Andrey Sidorov <sidorares@yandex.ru>",
    "Douglas Christopher Wilson <doug@somethingdoug.com>",
    "Diogo Resende <dresende@thinkdigital.pt>",
    "Nathan Woltman <nwoltman@outlook.com>"
  ],
  "homepage": "https://github.com/felixge/node-mysql",
  "repository": "felixge/node-mysql",
  "dependencies": {
    "bignumber.js": "2.3.0",
    "readable-stream": "1.1.14",
    "sqlstring": "2.0.1"
  },
  "devDependencies": {
    "after": "0.8.1",
    "eslint": "2.11.1",
    "istanbul": "0.4.3",
    "require-all": "2.0.0",
    "rimraf": "2.2.8",
    "timezone-mock": "0.0.0",
    "mkdirp": "0.5.1",
    "urun": "0.0.8",
    "utest": "0.0.8"
  },
  "files": [
    "lib/",
    "Changes.md",
    "License",
    "Readme.md",
    "index.js"
  ],
  "engines": {
    "node": ">= 0.6"
  },
  "scripts": {
    "lint": "eslint lib/**/*.js index.js test/**/*.js",
    "test": "node test/run.js",
    "test-ci": "node test/run-cov.js lcovonly",
    "test-cov": "node test/run-cov.js"
  }
}

 

这是代码,可以正确运行。

var mysql = require('mysql');  
      
var TEST_DATABASE = 'test';  
var TEST_TABLE = 'test';  
  
//创建连接  
var client = mysql.createConnection({  
  user: 'root',  
  password: '',  
});  

client.connect();
client.query("use " + TEST_DATABASE);

client.query(  
  'SELECT * FROM '+TEST_TABLE,  
  function selectCb(err, results, fields) {  
    if (err) {  
      throw err;  
    }  
      
      if(results)
      {
          for(var i = 0; i < results.length; i++)
          {
              console.log("%d\t%s", results[i].id, results[i].name);
          }
      }    
    client.end();  
  }  
);