Step-by-step guide on inserting data into a local sqlite database file using JavaScript

I have been attempting to insert data into a local SQLite database. I am able to achieve this, but unfortunately, I have to create a new table every time. I am hoping to find a way to insert the data without having to create a new table each time.

Even though I am successfully inserting the data into the table, creating a new table for each insertion is proving to be cumbersome.


$("#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();   

});

If there's a way to simply insert into the existing table, I would greatly appreciate your guidance. Thank you!

Answer №1

Is it necessary to create and write to the same file every time?

Instead of creating a new file each time, you could first check if the file already exists. If it does, simply reopen your database file located at "db/mydb.sqlite" and directly insert the data into the table. You can easily find the syntax for this online.

To update and read a database from the disk, you can use the following code:

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

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

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

Answer №2

Finally, I was able to locate the solution with your assistance!

$("#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();

});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The post() method in Express JS is functioning flawlessly in Firebase cloud function after deployment, however, it seems to encounter issues when running on a

https://i.stack.imgur.com/bIbOD.pngI am facing an issue with my Express JS application. Despite having both post() and get() requests, the post() request is not working on my local machine. It keeps throwing a 404 error with the message "Cannot POST / ...

Is async/await necessary even if the outcome is not important to me?

Imagine I have an API call that performs X and I convert it into asynchronous code using async/await: export default async (req: NextApiRequest, res: NextApiResponse) => { let success = await sendEmail({ //... }); return res.status(200) ...

Zapier tool: transmit data using a GET request

I'm currently working on integrating the intouch API into Zapier. Interestingly, the API is designed to accept queries within the body of GET requests instead of as parameters. While this setup works perfectly in Postman, I've encountered an iss ...

Warning: Unhandled promise rejection - Issue with casting data

I'm encountering an issue when attempting to access one of my routes using a GET request. Shown below is my Item model: models/item.js const { Schema, model } = require('mongoose'); const ItemSchema = new Schema({ name: { type: ...

Problem with deleting or substituting symbols and character codes within a String

I am attempting to send an object called dataO from Node.js/Express/EJS to the client side. On the Node.js script side: var dataO = {"first":[20000, 14000, 12000, 15000, 18000, 19000, 22000], "second":[12000, 11000, 18000, 12000, 19000, 14000, 26000]}; var ...

Tips for sending a timestamp as input to a stored procedure in TypeScript with the mssql module

Currently, I am utilizing the mssql npm package to communicate with SQL server. I have encountered a dilemma where the variable (which is of type TIMESTAMP in sql server) fetched from a stored procedure is returned as a byte array. Now, I need to pass this ...

Ensure that you utilize the import statement for loading ES modules in NODEJS to address the error encountered in B

I have recently started working with Babel and have some experience in Node.js. In my package.json file, I have dependencies related to Babel such as "@babel/preset-react": "^7.10.4", "@nuxtjs/eslint-config": "^0.0.1", "babel-cli": "^6.26.0". This project ...

The error message "Error: 'x' is not a defined function or its output is not iterable"

While experimenting, I accidentally discovered that the following code snippet causes an error in V8 (Chrome, Node.js, etc): for (let val of Symbol()) { /*...*/ } TypeError: Symbol is not a function or its return value is not iterable I also found out ...

Troubleshooting an electron application in Visual Studio Code

Can someone assist me with the following request? I am working on an electron app, which is a very simple quick start app. I am using Visual Studio Code to view the code and running the project from the terminal window with the command "npm start", which ...

Encountering a faulty handshake or ECONNRESET error connection in Azure Mysql while using

Issues with connecting to a mysql database hosted in Azure using an express.js app and KNEX have been troublesome. While I can successfully connect to the database from the console command or mysql workbench, my node app fails to do so. The connection ob ...

Data is not found in req.body when making a fetch request

I have been attempting to send a fetch request to my server, but I am consistently receiving an empty req.body. Here is the client-side script: const form = document.getElementById('form1') form.addEventListener('submit', (e) => ...

Two users are attempting to book two different appointments at the same time in Node.js utilizing MongoDB. However, only one user will

Within the functionality of my application, users have the ability to reserve a booking for time XYZ, as long as that specific time slot is still available. However, imagine if another user is also trying to book time XYZ simultaneously with the first us ...

What is the best way to create a redirect in Nuxt.js using a component method instead of the fetch method?

I'm currently working with nuxtjs and I am trying to figure out how to redirect the user after they have logged in. I've been having trouble getting the redirect() method to work within my function: loginUser: function () { if (this.isValid ...

NodeJS file execution through a stored procedure

Everything I've come across regarding the topic revolves around using a NodeJS program to call a stored procedure. Inquiring: Is it feasible to reverse this process? Can a stored procedure be designed to call/execute a NodeJS file/program instead? I& ...

Setting up NodeJS on Ubuntu 13.10

In the past, I have always compiled NodeJS from source. However, this time I decided to use the default apt repository for easier updates. Unfortunately, I'm having some trouble understanding what's happening. When I run the command: sudo ap ...

Deleting a variable parameter's length in Firebase Cloud Function

Here is a code snippet that I am working with: //index.js export const deletePicture = functions.region("europe-west1").database .ref("galleries/{galleryId}/{pictureId}") .onDelete(pictures.deletePicture) //pictures.js export const deletePicture = (s ...

Server hanging on loading in Node.js

My node.js server appears to be stuck loading indefinitely. Here is the excerpt of my code: var express = require('express'); const cors = require('cors'); var session = require('express-session'); var passport = require(&apos ...

Tips for running two elixir tasks consecutively?

Check out this piece of code: var gulp = require('gulp'), fs = require('fs'); gulp.task('taskOne', function() { return gulp.src('folder1/file1.js') .pipe(gulp.dest('folder2')); }); gulp.t ...

The URL retrieved on the React client-side does not align with the URL that was originally requested on the server

Currently, I'm developing a small app using nodejs-express-react. The issue I'm facing is related to sending a request to the Google Analytics Management API server-side and then attempting to retrieve the response from the client-side. Unfortuna ...

Include images in the form of .png files within the td elements of a table that is dynamically generated in the index

I have successfully created a table using embedded JavaScript with the help of messerbill. Here is the code: <table id="Table1"> <tr> <th>Kickoff</th> <th>Status</th> <th>Country</th> < ...