码迷,mamicode.com
首页 > 数据库 > 详细

nodejs上使用sql

时间:2017-10-06 23:08:30      阅读:296      评论:0      收藏:0      [点我收藏+]

标签:文件   down   style   sql   ons   color   nod   nload   mysql连接   

1.首先本地要安装mysql, https://www.mysql.com/downloads/.

2.在node中连接mysql,要安装mysql驱动,也就是npm安装mysql模块:npm i mysql

3.在js文件中引入mysql模块:var mysql = require(‘mysql‘);

4.创建mysql连接:

 1 var mysql = require(‘mysql‘);
 2 
 3 var con = mysql.createConnection({
 4   host: "localhost",
 5   user: "yourusername",
 6   password: "yourpassword"
 7 });
 8 
 9 con.connect(function(err) {
10   if (err) throw err;
11   console.log("Connected!");
12 });

这里createConnection中的参数是本地数据库的地址、用户名和密码。

5.开始使用mysql:

上面代码创建的con对象有个query方法,用来对数据库进行读写:

1 con.connect(function(err) {
2   if (err) throw err;
3   console.log("Connected!");
4   con.query(sql, function (err, result) {
5     if (err) throw err;
6     console.log("Result: " + result);
7   });
8 });

其中line 4 的sql参数是一个sql语句;result则是数据库查询返回的结果。

其他sql操作都是这样一个模式,所以这两天特别复习了sql...

 

nodejs上使用sql

标签:文件   down   style   sql   ons   color   nod   nload   mysql连接   

原文地址:http://www.cnblogs.com/alan2kat/p/7633164.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!