nodejs+mysql入门实例
来源:互联网 发布:易语言魔域登陆器源码 编辑:程序博客网 时间:2024/06/05 09:09
此前我已准备好mysql,使用的是PHP的组合包Appserv
手动添加数据库依赖:
在package.json的dependencies中新增, “mysql” : “latest”,
{ "name": "news", "version": "0.0.0", "private": true, "scripts": { "start": "node ./bin/www" }, "dependencies": { "body-parser": "~1.13.2", "cookie-parser": "~1.3.5", "debug": "~2.2.0", "express": "~4.13.1", "jade": "~1.11.0", "morgan": "~1.6.1", "serve-favicon": "~2.3.0", "mysql":"latest" }}
然后使用命令:
npm install
或
使用命令安装mysql并添加依赖:
npm install mysql -save
官方例子:
//连接数据库var mysql = require('mysql');var connection = mysql.createConnection({ host: '数据库地址如:localhost', user: '数据库用户名', password: '密码', database:'数据库名'});connection.connect();//查询connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) { if (err) throw err; console.log('The solution is: ', rows[0].solution);});//关闭连接connection.end();
运行node
这样Nodejs连接上了MySQL
可是这样真的就连上了吗?还是弄个表出来查下比较妥,下面在数据库:test下创建一个表名为:mytable
-- -- 数据库: `test`-- -- ---------------------------------------------------------- -- 表的结构 `mytable`-- CREATE TABLE `mytable` ( `name` varchar(255) NOT NULL) ENGINE=MyISAM DEFAULT CHARSET=utf8;-- -- 导出表中的数据 `mytable`-- INSERT INTO `mytable` VALUES ('名称1');INSERT INTO `mytable` VALUES ('名称2');
修改上面例子的查询语句
//连接数据库var mysql = require('mysql');var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'open00', database:'test'});connection.connect();//查询connection.query('select * from `mytable`', function(err, rows, fields) { if (err) throw err; console.log('查询结果为: ', rows);});//关闭连接connection.end();
运行node
确实是能查询的喲!我突然相信真爱了。。。
更多mysql例子:
https://www.npmjs.com/package/mysql
阅读全文
0 0
- nodejs+mysql入门实例
- nodejs连接mysql实例
- Angular4+NodeJs+MySQL 入门-01
- nodejs入门--path模块及实例(cs)
- nodejs中express 入门小实例
- 【Node】nodejs+express+mongodb入门实例
- 【Node】nodejs+express+mongodb入门实例(二)
- Angular4+NodeJs+MySQL 入门-05 接口调用
- Angular4+NodeJs+MySQL 入门-06 接口配置
- MySQL索引入门实例
- Angular4+NodeJs+MySQL 入门-02 MySql操作类
- nodejs入门
- Nodejs入门
- NodeJS入门
- nodejs入门
- nodejs入门
- Nodejs入门
- nodejs入门
- bootstrapvalidator校验验第三方插件
- Android菜单详解 使用上下文菜单ContextMenu
- < openCV > 最大稳定极值区域(MSER-Maximally Stable Extremal Regions)
- jenkins weblogic 自动部署
- Android学习笔记1-1--数据3--Bundle
- nodejs+mysql入门实例
- 安卓截屏分享功能实现
- STM32单片机GPIO资源理解以及上下拉选择探讨
- GLSL 基础量定义
- linux信号系列文终结篇:信号的捕捉(含mysleep的实现)
- Visualforce Page中的执行顺序
- poj-1704
- Android学习笔记1-2--通信1--HTTP
- spring MVC 服务器问题