登录
注册
node.js 学习社区
nodejs直接操作mysql 语句

金正日

2015-01-01 12:23

首先要安装node-mysql

$ npm install mysql

mysql test库建立users表

use test;
create table `users` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
  `username` VARCHAR(64) NOT NULL ,
  `password` VARCHAR(64) NOT NULL ,
  `created` datetime NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8  

连接数据库

var sys = require('sys');
var Client = require('mysql').Client;
var client = new Client();
client.user = 'root';
client.password = 'password';

client.connect(function(error, results) {
  if(error) {
    console.log('Connection Error: ' + error.message);
    return;
  }
  console.log('Connected to MySQL');
});

打开数据库

ClientConnectionReady = function(client){
    client.query('use test', function(error, results) {
        if(error) {
            console.log('ClientConnectionReady Error: ' + error.message);
            client.end();
            return;
        }
    });
};

完成数据库操作程序

var sys = require('sys');

var Client = require('mysql').Client;
var client = new Client();

client.user = 'someuser';
client.password = 'password';

console.log('Connecting to MySQL...');

client.connect(function(error, results) {
  if(error) {
    console.log('Connection Error: ' + error.message);
    return;
  }
  console.log('Connected to MySQL');
  ClientConnectionReady(client);
});

ClientConnectionReady = function(client){
    client.query('USE test', function(error, results) {
        if(error) {
            console.log('ClientConnectionReady Error: ' + error.message);
            client.end();
            return;
        }
        ClientReady(client);
    });
};

ClientReady = function(client){
  var values = ['Chad', 'Lung', 'Hello World'];
  client.query('INSERT INTO users SET username = ?, password = ? , message = ?', values,
    function(error, results) {
      if(error) {
        console.log("ClientReady Error: " + error.message);
        client.end();
        return;
      }
      console.log('Inserted: ' + results.affectedRows + ' row.');
      console.log('Id inserted: ' + results.insertId);
    }
  );
  GetData(client);
}

GetData = function(client){
  client.query(
    'SELECT * FROM users',
    function selectCb(error, results, fields) {
      if (error) {
          console.log('GetData Error: ' + error.message);
          client.end();
          return;
      }
      // Uncomment these if you want lots of feedback
      //console.log('results:');
      //console.log(results);
      //console.log('field metadata:');
      //console.log(fields);
      //console.log(sys.inspect(results));

      if(results.length > 0)
      {
        var firstResult = results[0];
        console.log('First Name: ' + firstResult['username']);
        console.log('Last Name: ' + firstResult['password']);
        console.log('created: ' + firstResult['created']);
      }
  });

  client.end();
  console.log('Connection closed');
};

回复 · 0

发表回复

你可以在回复中 @ 其他人