Node.js之mysql增删改查

1.安装库

1
npm install mysql

2.编写db.js(用作公共模块)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//连接MySQL数据库
var mysql = require("mysql");

var pool = mysql.createPool({
host:"127.0.0.1",
user:"root",
password:"123456",
database:"wordpress",
port:3306
});


function query(sql,callback){
pool.getConnection(function(err,connection){
connection.query(sql, function (err,rows) {
callback(err,rows);
connection.release();
});
});
}

exports.query = query;

node.js获取时间

1.Node.js安装时间库

1
npm install -g silly-datetime 或 npm install silly-datetime

2.使用代码

1
2
3
var sd = require('silly-datetime');
var time=sd.format(new Date(), 'YYYY-MM-DD HH:mm');
console.log(time);

展示效果如下:

JSON.stringify()和JSON.parse()的作用

(1)JSON.stringify() 从一个对象中解析出字符串

JSON.stringify({“a”:”1”,”b”:”2”})

结果是:”{“a”:”1”,”b”:”2”}”

(2)JSON.parse()从一个字符串中解析出JSON对象

var str = ‘{“a”:”1”,”b”:”2”}’;

JSON.parse(str);

结果是:Object{a:”1”,b:”2”}

应用场景:

针对(1),比如后台Java对应的RequestMapping参数列表中的参数为一个对象时,前台多个传输需要经过JSON.stringify()处理,否则会出现参数解析异常。

针对(2),比如向后台请求,后台返回一大堆字符串,这时前台页面渲染需要将其以对象的形式展现,这时可以用到JSON.parse()。

Error: listen EADDRINUSE :::3000

错误详细信息如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

events.js:183

throw er; // Unhandled 'error' event

^



Error: listen EADDRINUSE :::3000

at Server.setupListenHandle [as _listen2] (net.js:1360:14)

at listenInCluster (net.js:1401:12)

at Server.listen (net.js:1485:7)

at Function.listen (E:\VsCode\mock-github-api\node_modules\express\lib\appli cation.js:618:24)

at Object.<anonymous> (E:\VsCode\mock-github-api\index.js:180:5)

at Module._compile (module.js:653:30)

at Object.Module._extensions..js (module.js:664:10)

at Module.load (module.js:566:32)

at tryModuleLoad (module.js:506:12)

at Function.Module._load (module.js:498:3)

npm ERR! code ELIFECYCLE

npm ERR! errno 1

npm ERR! mock-github-api@1.0.0 start: `node index`

npm ERR! Exit status 1

npm ERR!

npm ERR! Failed at the mock-github-api@1.0.0 start script.

npm ERR! This is probably not a problem with npm. There is likely additional log ging output above.



npm ERR! A complete log of this run can be found in:

npm ERR! D:\Program Files\nodejs\node_cache\_logs\2019-03-19T06_44_19_978Z-d ebug.log