express连接数据库 读取表

connection 连接数据库

   connection.query 查询表
 
1.依赖 
const mysql = require('mysql');
  
连接数据库代码
 
 var connection = mysql.createPool({      //创建mysql实例
            host:'localhost',
            port:'3306',
            user:'root',
            password:'root',
            database:'test'
        });

        connection.getConnection(function (err,connection) { // 使用连接池  
            if(err){  
                console.log('与MySQL数据库建立连接失败!');  
                console.log('错误信息为:' + err);  
            }  
            else{  
                console.log('与MsSQL数据库建立连接成功!'); 
            }
        });

  查询表格代码

connection.query('SELECT * FROM types', function(err,result){
                resolve();
                console.log(result);
            });

 添加数据

 

connection.query("insert into user(name,age) values('"+name+"','"+ age +"')",function(err,rows){
        if(err){
            res.send("新增失败"+err);
        }else {
            res.redirect("/users");
        }
    });

  删除数据

var id = param.id;
connection.query('DELETE FROM types WHERE id = '+id+'',         function(err,result){
                resolve(result);
 });

  

 更新数据

new Promise((resolve, reject)=>{
            var left = "1,2,3,4,5";
            // param.left;
            var right = "1,2,3,4";
            //param.right;
            var id = 1;
            connection.query("update end set rightIn = '"+right+"', leftIn = '"+left+"' where id = '"+id+"'", function(err,result){
                resolve(result);
            });
        });

  

posted on 2019-09-02 15:17  chenyi4  阅读(641)  评论(0编辑  收藏  举报

导航