• Nodejs操作MySQL数据库


    https://github.com/mysqljs/mysql

     

      如何用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();
    
        });
    
    }
    复制代码

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

  • 相关阅读:
    Python之旅.第十章.mysql..
    Python之旅.第十章.mysql.
    Python之旅.第十章.mysql.
    Python之旅.第十章.mysql。
    Mac 移动光标和删除
    网络编程——socket开发
    闭包(closure)
    命名空间 and 作用域
    Function
    for循环的禁忌
  • 原文地址:https://www.cnblogs.com/sexintercourse/p/11669029.html
Copyright © 2020-2023  润新知