node.js数据库相关

来源:互联网 发布:资源搜索软件 编辑:程序博客网 时间:2024/06/05 20:01

1、node.js连接mysql并取数据

npm install mysql

mysql.js内容:

var mysql = require('mysql');var connection = mysql.createConnection({  host     : '1.1.1.1',  user     : 'root',  password : 'pwd'});connection.connect();connection.query("use weixin");connection.query("select * from wxfigure limit  3", function(err, rows, fields){    if (err) throw err;    console.log(rows);});connection.end();

运行结果

[ { id: 1,    cid: 1,    fname: '最帅快递小哥',    fpinyin: 'zuishuaikuaidixiaoge',    orderid: 100,    uptime: 1418124356 },  { id: 2,    cid: 1,    fname: '赌王何鸿',    fpinyin: 'duwanghehong',    orderid: 100,    uptime: 1417412161 },  { id: 3,    cid: 1,    fname: '徐才厚',    fpinyin: 'xucaihou',    orderid: 100,    uptime: 1418124348 } ]

2、node.js连接redis

npm install redis
redis.js

var redis = require("redis"),  client = redis.createClient(6379, "23.88.238.6");    client.on("error", function(err){     console.log("Error: " + err);  });    client.on("connect", function(){      // start server();      console.log("Start");  }); client.set("name_key", "hello world", function(err, reply){      console.log(reply.toString());  });    client.get("name_key", function(err, reply){      console.log(reply.toString());  }); client.quit();

输出

StartOKhello world

memcache

var memcache = require('memcache');var client = new memcache.Client(11211, "1.1.1.1");client.on('connect', function(){// no arguments - we've connectedconsole.log("start");  });client.on('close', function(){console.log("close");  // no arguments - connection has been closed});client.on('timeout', function(){console.log("timeout");  // no arguments - socket timed out});client.on('error', function(e){console.log("error");  // there was an error - exception is 1st argument});// connect to the memcache server after subscribing to some or all of these eventsclient.connect()client.set('key', 'value', function(error, result){// lifetime is optional. the default is// to never expire (0)}, 1);client.get('key', function(error, result){console.log(result);  // all of the callbacks have two arguments.// 'result' may contain things which aren't great, but// aren't really errors, like 'NOT_STORED'});client.close();




0 0
原创粉丝点击