nodejs上使用sql

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...

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