Can I store a JavaScript Object in a mySQL database?

前端 未结 5 523
谎友^
谎友^ 2021-02-07 20:59

I am gathering data from a webpage visitor and putting it into a JavaScript object I create. But later I want to be able to reference the data they entered.

I have acce

相关标签:
5条回答
  • 2021-02-07 21:19

    Store a JSON.stringified version of your object in the database, then JSON.parse it when you want the object back again. It would look something like this:

    var myObj = {some: data, other: stuff};
    var myObjString = JSON.stringify(myObj);
    // store string in mySQL database here
    
    // load string from database
    var myJSONString = //mySQL database call
    var myLoadedObj = JSON.parse(myJSONString);
    
    0 讨论(0)
  • 2021-02-07 21:25

    Yes Actually It can be done.

    con.connect(function(err){
    var sql = "INSERT INTO books SET ?";  //books -- <tablename>
    if(err) console.dir("Error: "+err.message);
    var values = {
        "bname": "Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future",
        "author": "Elon Musk",
        "genre": "Technology",
        "bookcount": "5"
    };
    con.query(sql, [values], function(err, result){
       if (err) throw err;
       else console.dir("Successfully inserted the row in table.");
          console.log(result);
    });
    }); 
    

    But, along with this you have to satisfy these points,

    • value should be object i.e., value={ "name":"property" }
    • It should not be an array i.e., values = [ {}, {} ]
    • Imp. - It should not have primary id column.

    Hope it helps.

    0 讨论(0)
  • 2021-02-07 21:26

    Just store it as a JSON object in a field using the varchar or text data type.

    0 讨论(0)
  • 2021-02-07 21:29

    No, you can't, at least not as it is.

    You might be able serialise it to a string. If it consists entirely of arrays, simple objects, and the other data types supported by the JSON format (which it probably will do if it is user supplied data (the main exception being if binary files are uploaded)), then you could use a JSON serializer to do so. Modern browsers provide the JSON object for this purpose and json2.js will polyfill for older browsers. You could then store the string in the database.

    Not breaking it into separate parts does throw away the many of the advantages of using a relational database though (i.e. the relationships and the ability to perform useful searches).

    0 讨论(0)
  • 2021-02-07 21:40

    Take a look at JSON. You can use something like jQuery to serialize form data and send it off to the server. Also you could just use plain old forms, and process input on the server side.

    0 讨论(0)
提交回复
热议问题