通常在 Node.JS 开发中我们经常涉及到操作数据库, 尤其是 MySQL, 作为应用最为广泛的开源数据库则成为我们的首选, 本篇就来介绍下 Node.JS 连接 MySQL 数据库的方法, 希望对大家有所帮助.
Node.JS 连接 MySQL 数据库的步骤:
1, 安装 MySQL
下载 MySQL, 并进行安装. 安装完, 会引导你对数据库进行配置, 设置 root 密码以及创建普通用户以及密码.
2, 安装 Node-MySQL
通过 NPM 安装 MySQL 的软件包, 通过它方便快速调用函数连接 MySQL 数据库. 进入项目文件夹, 执行以下命令:
NPM install MySQL --save
安装完, 在项目文件夹的 node_modules 目录下会生成 MySQL 的目录.
3, 连接数据库:
- var MySQL = require('mysql');
- var connection = MySQL.createConnection({
- host: 'localhost',
- user: 'root',
- password: '123456',
- database: 'test'
- });
- connection.connect();
- connection.query('SELECT 1 + 1 AS solution',
- function(error, results, fields) {
- if (error) throw error;
- console.log('The solution is:', results[0].solution);
- });
连接基本参数
host 主机名, localhost 代表本地
user MySQL 用户
password 密码
database 连接的数据库
client.connect() 连接数据库
client.query() 执行 SQL 语句
client.end() 关闭连接.
然后通过 node TestMysql.JS 执行程序, 确保你在执行之前已经启动了 MySQL 服务.
抛出源码, 蹬蹬蹬~~~~
- var Mysqlconnect = require('mysql');
- var sql = Mysqlconnect.createConnection({
- host:'localhost',
- user:'root',
- password:'xxxx',
- database:'trip'
- });
- sql.connect();
- /* GET users listing. */
- router.get('/', function(req, res, next) {
- sql.query("select * from tour",[],function(err,data){
- console.log(data);
- res.send(data);
- });
- });
- // 登录
- router.post('/login', function(req, res, next) {
- console.log(req.body.username);
- sql.query("select * from user_app where username = ? and password = ?",
- [req.body.username,req.body.password],function(err,data){
- console.log(data);
- if(err){
- console.log(err);
- return;
- }
- res.send(data);
- });
- });
- // 注册
- router.post('/register', function(req, res, next) {
- console.log(req.body.username);
- sql.query("insert into user_app (username,password,phone) value (?,?,?)",
- [req.body.username,req.body.password,req.body.phone],function(err,data){
- console.log(data);
- if(err){
- console.log(err);
- return;
- }
- res.JSON({res_code:0});
- });
- });
来源: http://www.css88.com/qa/node-js/12685.html