2.08.2009

Saving Javascript Objects to an SQL Database

Why create intermediate files when you can just store everything in a database? With the ability to store information on local databases like SQ lite and SQL servers being given away like candy from every web hosting service why not use their convenience and security for your websites.

I am going to post some code I wrote to directly save javascript objects to an SQLite database using Google gears. It's an example of writing a single method to save any type of object and I think changes the way we think about saving objects. Correct me if I am wrong, but this seems to be the least amount of code from any programming language for saving objects to an SQL database.

  1. function addSQLite(obj, table) {

  2. query = "INSERT INTO " + table + " VALUES (";

  3. z = 0;

  4. for(x in obj) {

  5. switch (typeof(obj[x])) {


  6. case 'string':

  7. if(z>0) query += ",";

  8. query += "'" + obj[x] + "'"

  9. break;


  10. case 'number':

  11. if(z>0) query += ",";

  12. query += obj[x];

  13. break;

  14. }

  15. z++;

  16. }

  17. query += ")"

  18. db.execute(query);

  19. }



This basically just puts a string together based on any objects properties. All you would have to do it make sure there is a table in the database with the same properties and you have yourself an incredibly versitale SQL function.

No comments:

Post a Comment