【问题标题】:Select, Handle and Insert/Update JSON data type选择、处理和插入/更新 JSON 数据类型
【发布时间】:2018-04-26 13:26:18
【问题描述】:

我正在使用带有 MySQL 数据库的 Node.JS 服务器,我刚刚意识到 MySQL 支持 JSON 作为数据类型。

根据我之前的陈述,我该如何 a) SELECT JSON,b) 在我的 node.js 代码中处理结果,c) 然后 UPDATEJSON 中的 DB 条目再次出现?

a 和 b 部分的代码示例:

sql.getConnection((err, con)=>{
            con.query("SELECT test FROM test", (error, row)=>{
            con.release();
            if(error) throw error;          
            console.log(row[0].test);
            });
});

这段代码返回:{"entryid": {"a": 1, "b": 2, "c": 3}}

现在如果我尝试做这样的事情:console.log(row[0].test./*any sub-key here*/); 它会返回undefined

【问题讨论】:

    标签: mysql json node.js


    【解决方案1】:

    我设法通过忽略 MySQL 推荐的语法并实现我自己的邪恶方法来解决我的问题,正如您在 Gist 中看到的那样。

    let mysql = require('mysql');
    let dbconn = {
        host: "localhost",       // make sure to replace with your own configuration
        user: "root",            // make sure to replace with your own configuration
        password: "password",    // make sure to replace with your own configuration
        connectionLimit: 100,    // make sure to replace with your own configuration
        database: "db"           // make sure to replace with your own configuration
    };
    let sql = mysql.createPool(dbconn);
    let jsonObj;
     /*
        * let's assume that the stored JSON has the following structure:
        *
        * "master_key" : {
        *      sub_key1: "test1",
        *      sub_key2: "test2",
        *      sub_key3: {
        *          sub_key4: "test4"
        *      }
        *  
    */
    
    sql.getConnection((err, conn) => {
        if(err) throw err;
        // We can SELECT it
        conn.query("SELECT json_Column FROM test_Table",(error, row) => {
            conn.release();
            if(error) throw error;
            jsonObj = JSON.parse(row[0].json_Column); //you can now handle the json keys as usual
            // jsonObj.master_key || jsonObj.master_key.sub_key1 || jsonObj.master_key.sub_key3.sub_key4 || however you want
        });
    
        // We can INSERT it
        jsonObj = {/*your JSON here*/};
        conn.query("INSERT INTO test_Table(json_Column) VALUES ?", [JSON.stringify(jsonObj)],(error, row) => {
            conn.release();
            if(error) throw error;
            console.log(row[0]);
        });
    
        // We can UPDATE it
        jsonObj = {/*your JSON here*/};
        conn.query("UPDATE test_Table SET json_Column = ?", [JSON.stringify(jsonObj)],(error, row) => {
            conn.release();
            if(error) throw error;
            console.log(row[0]);
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-12
      • 1970-01-01
      • 2018-02-25
      • 1970-01-01
      相关资源
      最近更新 更多