How to do a simple insert into the local database file sqlite with javascript

1.4k Views Asked by At

I try to insert data into a local database sqlite. Its possible. I can do it . But I have to create a new table every time. I try to do it without creating a new table...

I already insert the data into the table but I had to create a table every time.

     $("#ecris").click( function() 
        {          

              var fs = require("fs");         
              var sql = require("./js/sql.js"); 
              var db = new sql.Database();                   
              db.run("CREATE TABLE test (col1, col2);");

              db.run("INSERT INTO test (col1, col2) VALUES ('8','4564')"); 
;  
              var data = db.export();

              var buffer = new Buffer(data);
              fs.writeFileSync("bd/mybd.sqlite", buffer );
              db.close();   



        });

I just need the insert into the existing table... thanks a lot

2

There are 2 best solutions below

2
On BEST ANSWER

Why creating & writing to same file everytime,

instead check if file already exists, then reopen your db file "bd/mybd.sqlite" and directly insert data to table, you can get syntax easily on net.

Update to read a database from the disk:

   var fs = require('fs');
   var SQL = require('sql.js');
   var filebuffer = fs.readFileSync('test.sqlite');

  // Load the db
  var db = new SQL.Database(filebuffer);

Ref: https://github.com/kripken/sql.js/blob/master/README.md

0
On

finally find thanks for your help !

$("#ecris").click( function() 
{          

     var fs =  require('fs');         
     var sql = require("./js/sql.js");      
     var filebuffer = fs.readFileSync("bd/mybd.sqlite"); 
     var db = new sql.Database(filebuffer);
      db.run("INSERT INTO test (col1, col2) VALUES ('gerald','coucou')");
     var data = db.export();
     var buffer = new Buffer(data);
     fs.writeFileSync("bd/mybd.sqlite", buffer );
     db.close();

});