Nodejs学习笔记-直接连接Mysql
2017-10-25 本文已影响46人
莫名FCJ
安装Mysql
wget http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm
rpm -ivh mysql-community-release-el7-5.noarch.rpm
yum -y install mysql-server
service mysqld start
mysql -u root
update user set Password=password('123456') where User='root';
service mysqld restart
mysql -u root -p'123456'
创建数据库表
create database test;
use test;
create table user(
uid int not null primary key auto_increment,
uname varchar(100) not null,
pwd varchar(100) not null
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
安装Mysql模块
npm install mysql --g
代码
https://github.com/fengchunjian/nodejs_examples/tree/master/mysql
//mysqlBean.js
var mysql = require("mysql");
var connection = mysql.createConnection({
host : "localhost",
user : "root",
password : "123456",
database : "test",
port : "3306"
});
connection.connect(function(err) {
if (err) {
console.log("connect failed:" + err);
return;
}
console.log("connect ok");
});
var userAddSql = "insert into user(uname, pwd) values(?, ?)";
var param = ["bbb", "bbb"];
connection.query(userAddSql, param, function(err, rs) {
if (err) {
console.log("insert failed:" + err);
return;
}
console.log("insert ok");
});
connection.query("select * from user where uid>?", [0], function(err, rs) {
if (err) {
console.log("select failed:" + err);
return;
}
for (var i=0; i<rs.length; i++) {
console.log("result:" + rs[i].uname);
}
});
connection.end(function (err) {
if (err) {
console.log("end failed:" + err);
return;
}
console.log("end ok");
});
参考文档
node.js教程14_直连mysql
http://edu.51cto.com//center/course/lesson/index?id=124540
nodejs_直连mysql(n14_mysql)
http://www.yuankuwang.com/web/index.php?r=respool/resview&rpid=47
CentOS 7 用yum安装 MySQL
http://www.linuxidc.com/Linux/2016-03/129683.htm