选择、处理和插入/更新json数据类型

h5qlskok  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(389)

我正在使用node.js服务器和mysql数据库,我刚刚意识到mysql支持json作为数据类型。
根据我之前的陈述,我该怎么做
SELECT JSON ,b)在my node.js代码中处理结果,c)然后 UPDATE 数据库条目在 JSON ?
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 .

8fsztsew

8fsztsew1#

好吧,我设法解决了我的问题,只是忽略了mysql推荐的语法,实现了我自己的邪恶方法,正如你在本文中看到的。

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]);
    });
});

相关问题