Asked 6 years ago
15 Nov 2017
Views 1413
lain

lain posted

how to connect SQLite3 in Electron js at node js

Electron js not working good with SQLite3 at node js.its working charm with experss framework with node js but now with Electron js , why SQLite3 not working with Electron js ?
jagdish

jagdish
answered Apr 24 '23 00:00

To connect to SQLite3 in an Electron app using Node.js, you can use the sqlite3 package, which is a Node.js package that provides SQLite3 bindings for Node.js.

Here's an example of how to use sqlite3 to connect to an SQLite database in an Electron app:

1.Install the sqlite3 package by running the following command in your terminal:



npm install sqlite3

2.In your Electron app, require the sqlite3 package at the top of your main process file:


const sqlite3 = require('sqlite3').verbose()

The verbose () function makes SQLite3 provide more detailed debug messages when something goes wrong.

3.Create a new database connection by creating a new sqlite3.Database object:


const db = new sqlite3.Database('./mydatabase.db')

In this example, my database.db is the name of the database file. You can replace it with the name of your own database file.

4.Use the db.run() method to execute SQL commands on the database. For example, you can create a new table in the database by running the following SQL command:


db.run('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)')

This will create a new table named users with two columns: id and name .

5.You can also use the db.all() method to retrieve data from the database. For example, you can retrieve all the rows from the users table by running the following SQL command:


db.all('SELECT * FROM users', (err, rows) => {
  if (err) {
    console.error(err.message)
  }
  console.log(rows)
})

This will retrieve all the rows from the users table and log them to the console.

6.Finally, when you're done using the database, you should close the connection by calling the db.close() method:


db.close()

That's it! You can use the sqlite3 package to connect to an SQLite database in an Electron app using Node.js.
Post Answer