Search code examples
node.jsinsertelectronsql.js

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


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


Solution

  • 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