nodejs mysql前后端数据_如何用nodejs操作MySql数据?

转载自品略图书馆 http://www.pinlue.com/article/2019/12/2423/469854736040.html

如何用nodejs操作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(); });}

是不是很简单啊,只要在你需要的地方添加方法名和对应的参数 ,就可以了

afec934c6490241e8fd738421c6c6cbe.png
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值