Node.JS 控制数据库的方法: 使用命令 NPM install MySQL --save 安装数据库的软件包, 然后在新建的项目中连接数据库, 就可以在 Node.JS 项目中对数据库进行删改查了.
Node.JS 控制 MySQL 数据的方法如下:
1, 开始在你的 node 项目中使用命令
NPM install MySQL --save
2, 在你的新建项目中引入代码
- // 引入数据库
- var MySQL=require('mysql');
- // 实现本地链接
- var connection = MySQL.createConnection({
- host: 'localhost',
- user: 'yf',
- password: '123456',
- database: 'yf'
- })
最好不好是用 root 会产生冲突
3, 之后就是增删改查啦, 附上代码
查询
- // 查找
- function select() {
- connection.connect(function (err) {
- if (err) {
- console.error('error connecting:' + err.stack)
- }
- console.log('connected as id' + connection.threadId);
- })
- connection.query('SELECT * FROM demo', function (error, results, fields) {
- if (error) throw error;
- console.log('The solution is:', results);
- });
- connection.end();
- }
添加
- // 添加
- function add() {
- let post = {
- id: 1,
- name: 'Hello MySql',
- age: 20,
- time: Date.now(),
- temp: 'deom'
- };
- let query = connection.query("INSERT INTO demo SET ?", post, function (error, results, fields) {
- if (error) throw error;
- })
- console.log(query.sql); //INSERT INTO posts 'id'=1, 'title'='Hello MySQL'
- }
修改
- // 修改
- function updeate() {
- connection.connect(function (err) {
- if (err) {
- console.error('error connecting:' + err.stack);
- }
- console.log('connected as id' + connection.threadId);
- });
- connection.query('UPDATE demo SET name=?where id?', ['update', 1], function (error, results, fields) {
- if (error) throw error;
- console.log('changed:' + results.changeRows + 'rows');
- });
- connection.end();
- }
删除
- // 删除
- function deletes() {
- connection.connect(function (err) {
- if (err) {
- console.error('error connecting:' + err.stack);
- return;
- }
- connection.query('DELETE FROM demo SET where id=?', [ 1], function (error, results, fields) {
- if (error) throw error;
- console.log('deleted:' + results.affectedRows + 'rows');
- });
- console.log('connected as id' + connection.threadId);
- connection.end();
- });
- }
来源: http://www.css88.com/qa/node-js/10796.html