node.js安装mysql包
npm install mysql
数据表(admin)如下:
link.js
var mysql = require('mysql');console.log("running server link mysql")//创建连接var connection = mysql.createConnection({ host : '127.0.0.1', user : 'root',//数据库的用户名 password : '123456',//数据库的密码 port: '3306',//数据库的端口号 database: 'test' //连接的数据库名});//开始连接connection.connect();//开始查询var sql = 'SELECT * FROM admin';connection.query(sql,function(err, results, fields) { if (err) { throw err; } var data=[];//保存数据 if(results){ // console.log(results) for(var key in results){ var a={}; a.id = results[key].id; a.user_name = results[key].user_name; a.age = results[key].age; a.sex = results[key].sex; a.create_dt = results[key].create_dt; data.push(a); } console.log(data); }else{ console.log("没有数据") } // console.log("fields", fields) connection.end(); });//增加数据 有两种方式// 第一种var add_sql = 'INSERT INTO admin(user_name,age,sex,create_dt) VALUES(?, ?, ?, ?)';var Params = ["names",15,1,"2020-12-12"];connection.query(add_sql,Params,function(err, result) { if(err){//报错 throw err; } console.log('way 1: INSERT ID:',result); });// 第二种var add_sql2 = 'INSERT INTO admin(user_name,age,sex,create_dt) VALUES("names",15,1,"2020-12-12")';connection.query(add_sql2,function(err, result) { if(err){//报错 throw err; } console.log('way 2: INSERT ID:',result); });//剩余的修改和删除操作类似