[NODEJS]DATABASE INSERT,SELECT,DELETE(SQLITE)

SQLITE는 로그인없이 사용 할 수 있는 가벼운 데이터베이스입니다.
데이터베이스 서버부분이 없기 때문에 db파일에 바로 접근해서 사용할 수 있습니다.
서버접속 없이 웹앱을 만들거나 모바일 앱을 만들 때 많이 사용합니다.
오픈 소스이며 자세한 내용은 https://sqlite.org 에서 확인 할 수 있습니다.

SQLITE is a lightweight database that can be used without logging in.
Since there is no database server part, you can directly access and use the db file.
It is often used when creating web apps or mobile phone apps without server access.
It is open source and more information can be found at https://sqlite.org.

1.SQLITE 함수(SQLITE FUNCTION)
– 아래 코드에서 사용된 SQLITE함수 입니다.
– This is the SQLITE function used in the code below.

.exec() : 일반적인 SQL 구문을 실행하며 파라미터를 직접적으로 조작(핸들링) 할 수 없습니다.
.run() : 이 방법은 일반적으로 INSERT, UPDATE, DELETE 등과 같이 데이터베이스를 수정하는 SQL 쿼리를 실행하는 데 사용됩니다. SQL 인젝션 공격을 방지하기 위해 매개변수화된 쿼리를 사용합니다.
.get() : SQLLITE의 데이터베이스에서 1행의 데이터만 가지고 옵니다.
.all() : 특정 기준에 따라 데이터베이스에서 여러 레코드를 검색하려고 할 때 일반적으로 사용됩니다.
.each(): SELECT 쿼리를 실행하여 데이터 테이블에서 데이터를 검색하는 데 사용됩니다. 검색된 데이터를 행단위로 반복해서 가져옵니다.

.exec() : General SQL statements are executed and parameters cannot be directly manipulated (handled).
.run():This method is typically used to execute SQL queries that modify the database, such as INSERT, UPDATE, DELETE, etc.It uses parameterized queries to prevent SQL injection attacks.
.get():Only one row of data is imported from the SQLLITE database.
.all():It’s commonly used when you expect to retrieve multiple records from the database based on certain criteria.
.each : Used to retrieve data from a data table by executing a SELECT query. Retrieves the searched data row by row repeatedly.

2.설치(install)
간단히 npm명령어로 설치 할 수 있습니다.
You can simply install it with the npm command.

#npm install sqlite sqlite3

3.데이터베이스접속(Database connection)
데이터베이스 접속을 위해서 open함수 또는 new sqlite3.Database()를 사용할 있습니다.
To connect to the database, you can use the open function or new sqlite3.Database().

1)모듈 임포트(module import)

const sqlite3 = require('sqlite3').verbose();
const { open } = require('sqlite');
const dbname = "member.db";

2)open()함수 사용(Using the open() function) or new sqlite3.Database()

  const db = await open({
        filename: 'member.db',
        driver: sqlite3.Database
  });
const db = new sqlite3.Database('member.db');

4.데이터입력(Data input) [ insertDB() ]
– members테이블이 존재하지 않으면 생성합니다.
– insert구문을 이용해서 데이터를 입력합니다.
– (?,?,?,) 이 부분에 id,username,room이 위치합니다.

– If the members table does not exist, it is created.
– Enter data using the insert statement.
– The id, username, and room are located in this part. (?,?,?,)

....      
     await db.exec(`
        CREATE TABLE IF NOT EXISTS members (
            idx INTEGER PRIMARY KEY AUTOINCREMENT,
            id TEXT,
            username TEXT,
            room TEXT
        );
      `);
    
      await db.run("INSERT INTO members (id, username, room) VALUES (?, ?, ?)", id, username,room);
      db.close();
....

5.모든 데이터 보기( View all data )[ showAllDB() ]
– members테이블의 모든데이터를 검색하고출력합니다.
– All data in the members table is searched and output.

  ...
   await db.each("SELECT * FROM members", (err, row) => {
    if (err) {
      console.error(err.message);
    }
    console.log(row.id, row.username, row.room);
  });
  
  db.close();
...

6.모든 데이터 삭제(delete all data)[ deleteAllDB() ]
– members테이블의 모든 데이터를 삭제합니다.
– Delete all data in the members table.

...
  await db.run('DELETE FROM members');
  await db.close();
...

7.함수 실행(Function excute)
– 코멘트처리 부분(//)을 삭제해서 실행합니다.
– Execute it by deleting the comment processing part ( // ).

//insertDB("240502","helloworld1","worldclass");
//showAllDB();
//deleteAllDB();

8.전체코드(Full code)

const sqlite3 = require('sqlite3').verbose();
const { open } = require('sqlite');
const dbname = "member.db";
//const db = new sqlite3.Database('member.db');

async function insertDB(id,username,room) {
/*
  const db = await open({
        filename: 'member.db',
        driver: sqlite3.Database
    });
*/   
const db = new sqlite3.Database(dbname);

      await db.exec(`
        CREATE TABLE IF NOT EXISTS members (
            idx INTEGER PRIMARY KEY AUTOINCREMENT,
            id TEXT,
            username TEXT,
            room TEXT
        );
      `);
    
      await db.run("INSERT INTO members (id, username, room) VALUES (?, ?, ?)", id, username,room);
      db.close();
}

async function showAllDB(){
  
  const db = new sqlite3.Database(dbname);
  await db.each("SELECT * FROM members", (err, row) => {
    if (err) {
      console.error(err.message);
    }
    console.log(row.id, row.username, row.room);
  });
  
  db.close();

}

async function deleteAllDB(){

  const db = new sqlite3.Database(dbname);
  await db.run('DELETE FROM members');
  await db.close();

}

//insertDB("240502","helloworld1","worldclass");
//showAllDB();
//deleteAllDB();


Leave a Reply

Your email address will not be published. Required fields are marked *