我正在使用带有MySQL数据库的Node.JS服务器,我才意识到MySQL支持JSON作为数据类型。
基于我之前的陈述,我如何a)// After this, the playerName field will be empty
[classScore removeObjectForKey:@"customName"];
// Saves the field deletion to the Parse Cloud
[classScore saveInBackground];
SELECT
,b)处理我的node.js代码中的结果,然后c)再次JSON
UPDATE
数据库条目JSON
1}}?
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
。
答案 0 :(得分:0)
我设法解决了我的问题,只是忽略了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]);
});
});