Hike News
Hike News

nodejs에서 Sqlite 사용하기

Person:

1
2
3
4
5
6
7
8
0. [제목:String], [설명:String], [제작자:String]를 sqlite로 db로 만든다.
1. node.js에서 ejs로 개발한다.
2. node.js에서 index.html로 요청이 들어올 시
index.ejs 파일을 읽어온다.
node.js에서 보낸 값으로
제목, 설명, 제작자의 정보를 출력한다.

6. index.html과 node.js 소스를 만들어주세요

ChatGPT:

  • 아래는 요구사항에 맞게 index.html과 node.js 소스 코드를 작성한 예시입니다. 주의: 이 예시는 실제 서버에서 동작하지 않으며, 개발 및 학습용으로만 사용해야 합니다.

index.html:

1
2
3
4
5
6
7
8
9
10
11
12

<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<h1><%= title %></h1>
<p><%= description %></p>
<p>제작자: <%= author %></p>
</body>
</html>

app.js (node.js):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

const express = require('express');
const app = express();
const ejs = require('ejs');
const sqlite3 = require('sqlite3').verbose();

// SQLite DB 연결
const db = new sqlite3.Database('mydb.db', (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the database.');
});

// 루트 경로에서 index.ejs 렌더링
app.get('/', (req, res) => {
// SQLite DB에서 데이터 조회
db.get('SELECT * FROM mytable', (err, row) => {
if (err) {
console.error(err.message);
return res.status(500).send('Internal Server Error');
}

// index.ejs 렌더링 및 데이터 전달
ejs.renderFile('index.ejs', {
title: row.title,
description: row.description,
author: row.author
}, (err, renderedHtml) => {
if (err) {
console.error(err.message);
return res.status(500).send('Internal Server Error');
}
res.send(renderedHtml);
});
});
});

// 서버 시작
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});

위의 코드 예시는 다음과 같은 과정을 수행합니다:

  1. index.html은 EJS 문법(<%= %>)을 사용하여 동적으로 제목, 설명, 제작자 정보를 표시하는 간단한 HTML 템플릿입니다.
  2. app.js는 Express와 EJS를 사용하여 웹 서버를 구성합니다.
  3. SQLite 데이터베이스를 연결하고, mytable에서 제목, 설명, 제작자 정보를 가져옵니다.
  4. 웹 서버에 들어오는 루트 경로 요청(http://localhost:3000/)에 대해 index.ejs 파일을 렌더링하여 클라이언트에 전달합니다.
  5. index.ejs는 SQLite DB에서 조회한 값으로 제목, 설명, 제작자 정보를 출력하고, 브라우저로 전달합니다.

이 예시 코드를 실행하려면 먼저 express, ejs, sqlite3 라이브러리를 설치해야 합니다. 프로젝트 폴더에서 아래 명령을 실행하세요:

1
2

npm install express ejs sqlite3

그리고 index.htmlapp.js 파일을 프로젝트 폴더에 생성한 후, SQLite DB 파일(mydb.db)을 생성하여 데이터를 채워넣어야 합니다. 데이터베이스 생성 및 테이블 작성은 이 예시의 범위를 벗어나므로 자세한 내용은 생략하겠습니다.

이후 아래 명령을 실행하여 서버를 실행합니다:

1
2

node app.js

웹 브라우저에서 http://localhost:3000/로 접속하면 index.html에 작성된 내용과 SQLite DB에서 조회한 값이 출력되는 페이지를 확인할 수 있습니다.

Person:

  • [제목:String], [설명:String], [제작자:String]를 sqlite로 db로 만들기 위해 해야할 일을 알려주세요

ChatGPT:

  • SQLite 데이터베이스를 만들고, 해당 데이터베이스에 [제목:String], [설명:String], [제작자:String]를 저장하기 위해 다음과 같은 일들을 해야 합니다:
  1. SQLite 설치: SQLite를 사용하려면 먼저 시스템에 SQLite를 설치해야 합니다. SQLite는 오픈 소스이며, 공식 웹사이트에서 다운로드하여 설치할 수 있습니다. 또는 시스템 패키지 관리자를 통해 SQLite를 설치할 수도 있습니다.
  2. 데이터베이스 파일 생성: SQLite는 파일 기반 데이터베이스를 사용합니다. 데이터를 저장할 SQLite 데이터베이스 파일을 생성해야 합니다.
  3. 데이터베이스 스키마 설계: 데이터베이스 스키마는 테이블의 구조를 정의합니다. 데이터베이스 테이블에는 [제목:String], [설명:String], [제작자:String]를 저장할 수 있는 컬럼이 필요합니다.
  4. SQLite 데이터베이스에 연결: 애플리케이션에서 SQLite 데이터베이스를 사용하려면 데이터베이스에 연결해야 합니다.
  5. 테이블 생성: 데이터베이스에 저장할 데이터를 담을 테이블을 생성해야 합니다. 위의 스키마 설계를 기반으로 테이블을 생성합니다.
  6. 데이터 추가: 테이블에 [제목:String], [설명:String], [제작자:String] 데이터를 추가합니다.

아래는 Node.js에서 SQLite를 사용하여 데이터베이스를 생성하고 테이블을 만들고 데이터를 추가하는 예시 코드입니다. Node.js에서 SQLite를 사용하려면 먼저 ‘sqlite3’ 모듈을 설치해야 합니다.

1
2

npm install sqlite3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

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

// 데이터베이스 파일 생성 및 연결
const db = new sqlite3.Database('mydb.db', (err) => {
if (err) {
console.error(err.message);
return;
}
console.log('Connected to the database.');

// 테이블 생성
db.run(`
CREATE TABLE IF NOT EXISTS mytable (
id INTEGER PRIMARY KEY,
title TEXT,
description TEXT,
author TEXT
)
`, (err) => {
if (err) {
console.error(err.message);
return;
}
console.log('Table "mytable" created.');

// 데이터 추가
const title = 'Sample Title';
const description = 'This is a sample description.';
const author = 'John Doe';

db.run('INSERT INTO mytable (title, description, author) VALUES (?, ?, ?)',
[title, description, author], (err) => {
if (err) {
console.error(err.message);
return;
}
console.log('Data inserted successfully.');

// 데이터베이스 연결 종료
db.close((err) => {
if (err) {
console.error(err.message);
return;
}
console.log('Database connection closed.');
});
});
});
});

위의 코드는 다음과 같은 작업을 수행합니다:

  1. ‘mydb.db’라는 SQLite 데이터베이스 파일을 생성하고 연결합니다.
  2. ‘mytable’이라는 테이블을 생성합니다. 해당 테이블에는 id(자동 생성된 고유 번호), title, description, author라는 컬럼이 있습니다.
  3. ‘mytable’에 샘플 데이터를 추가합니다. 이 예시에서는 하나의 레코드만 추가했습니다.
  4. 데이터베이스 연결을 종료합니다.

위의 예시 코드를 실행하면 ‘mydb.db’ 파일이 생성되고, ‘mytable’ 테이블이 생성되며, 샘플 데이터가 추가됩니다. 이제 앞서 작성한 Node.js와 EJS 코드에서 해당 데이터베이스를 사용하여 제목, 설명, 제작자 정보를 가져와서 렌더링할 수 있을 것입니다.

Person:

  • 위의 소스에서 브라우저에서 /input을 요청하면
    제목, 설명, 제작자를 입력하는 화면이 나온다.
    그곳에서 입력하면
    db에 저장되는 기능을 추가해줘

ChatGPT:

  • 앞서 작성한 코드에 “제목, 설명, 제작자를 입력하는 화면이 나오는 기능”을 추가하고, 사용자가 입력한 데이터를 SQLite 데이터베이스에 저장하는 기능을 구현해보겠습니다.

아래는 이러한 기능을 추가한 코드 예시입니다:

index.html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<h1><%= title %></h1>
<p><%= description %></p>
<p>제작자: <%= author %></p>

<h2>데이터 입력</h2>
<form action="/input" method="POST">
<label for="inputTitle">제목:</label>
<input type="text" id="inputTitle" name="title" required><br>

<label for="inputDescription">설명:</label>
<input type="text" id="inputDescription" name="description" required><br>

<label for="inputAuthor">제작자:</label>
<input type="text" id="inputAuthor" name="author" required><br>

<button type="submit">저장</button>
</form>
</body>
</html>

app.js (Node.js):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76

const express = require('express');
const app = express();
const ejs = require('ejs');
const bodyParser = require('body-parser');
const sqlite3 = require('sqlite3').verbose();

// SQLite DB 연결
const db = new sqlite3.Database('mydb.db', (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the database.');
});

// Body-parser 미들웨어 등록
app.use(bodyParser.urlencoded({ extended: true }));

// 루트 경로에서 index.ejs 렌더링
app.get('/', (req, res) => {
// SQLite DB에서 데이터 조회
db.get('SELECT * FROM mytable', (err, row) => {
if (err) {
console.error(err.message);
return res.status(500).send('Internal Server Error');
}

// index.ejs 렌더링 및 데이터 전달
ejs.renderFile('index.ejs', {
title: row.title,
description: row.description,
author: row.author
}, (err, renderedHtml) => {
if (err) {
console.error(err.message);
return res.status(500).send('Internal Server Error');
}
res.send(renderedHtml);
});
});
});

// 데이터 입력 페이지 렌더링
app.get('/input', (req, res) => {
ejs.renderFile('input.ejs', (err, renderedHtml) => {
if (err) {
console.error(err.message);
return res.status(500).send('Internal Server Error');
}
res.send(renderedHtml);
});
});

// 데이터 입력 처리
app.post('/input', (req, res) => {
const title = req.body.title;
const description = req.body.description;
const author = req.body.author;

// 데이터 삽입
db.run('INSERT INTO mytable (title, description, author) VALUES (?, ?, ?)',
[title, description, author], (err) => {
if (err) {
console.error(err.message);
return res.status(500).send('Internal Server Error');
}
console.log('Data inserted successfully.');
res.redirect('/');
});
});

// 서버 시작
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});

위의 코드 예시는 다음과 같은 변경을 수행합니다:

  1. index.html에 데이터 입력을 위한 form을 추가합니다. 사용자가 제목, 설명, 제작자를 입력하고 “저장” 버튼을 누르면 /input 경로로 POST 요청이 전송됩니다.
  2. app.js에 /input 경로에 대한 GET 및 POST 핸들러를 추가합니다. GET 요청 시 “input.ejs”를 렌더링하여 데이터 입력 페이지를 보여줍니다. POST 요청 시 사용자가 입력한 데이터를 SQLite 데이터베이스에 삽입합니다.
  3. 데이터 삽입 후에는 / 경로로 리다이렉션하여 변경된 데이터를 확인할 수 있도록 합니다.

위의 코드를 실행하고 http://localhost:3000/input에 접속하면 데이터 입력 페이지가 나타납니다. 사용자가 데이터를 입력하고 저장하면 SQLite 데이터베이스에 저장되고, 메인 페이지(http://localhost:3000/)에서 변경된 데이터를 확인할 수 있습니다.

Person:

  • 위의 form 입력화면인 index.html을 cms.html로 바꾸어주고 node.js에서 호출할 수 있도록 만들어주세요

ChatGPT:

  • Sure! 아래는 cms.html로 변경한 예시 코드입니다. 그리고 app.js에서 /cms 경로에 대한 핸들러를 추가하여 cms.html을 렌더링할 수 있도록 합니다.

cms.html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

<!DOCTYPE html>
<html>
<head>
<title>CMS - 데이터 입력</title>
</head>
<body>
<h2>데이터 입력</h2>
<form action="/input" method="POST">
<label for="inputTitle">제목:</label>
<input type="text" id="inputTitle" name="title" required><br>

<label for="inputDescription">설명:</label>
<input type="text" id="inputDescription" name="description" required><br>

<label for="inputAuthor">제작자:</label>
<input type="text" id="inputAuthor" name="author" required><br>

<button type="submit">저장</button>
</form>
</body>
</html>

app.js (Node.js):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76

const express = require('express');
const app = express();
const ejs = require('ejs');
const bodyParser = require('body-parser');
const sqlite3 = require('sqlite3').verbose();

// SQLite DB 연결
const db = new sqlite3.Database('mydb.db', (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the database.');
});

// Body-parser 미들웨어 등록
app.use(bodyParser.urlencoded({ extended: true }));

// 루트 경로에서 index.ejs 렌더링
app.get('/', (req, res) => {
// SQLite DB에서 데이터 조회
db.get('SELECT * FROM mytable', (err, row) => {
if (err) {
console.error(err.message);
return res.status(500).send('Internal Server Error');
}

// index.ejs 렌더링 및 데이터 전달
ejs.renderFile('index.ejs', {
title: row.title,
description: row.description,
author: row.author
}, (err, renderedHtml) => {
if (err) {
console.error(err.message);
return res.status(500).send('Internal Server Error');
}
res.send(renderedHtml);
});
});
});

// CMS 페이지 렌더링
app.get('/cms', (req, res) => {
ejs.renderFile('cms.html', (err, renderedHtml) => {
if (err) {
console.error(err.message);
return res.status(500).send('Internal Server Error');
}
res.send(renderedHtml);
});
});

// 데이터 입력 처리
app.post('/input', (req, res) => {
const title = req.body.title;
const description = req.body.description;
const author = req.body.author;

// 데이터 삽입
db.run('INSERT INTO mytable (title, description, author) VALUES (?, ?, ?)',
[title, description, author], (err) => {
if (err) {
console.error(err.message);
return res.status(500).send('Internal Server Error');
}
console.log('Data inserted successfully.');
res.redirect('/');
});
});

// 서버 시작
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});

위의 코드를 실행하고 http://localhost:3000/cms에 접속하면 데이터 입력 페이지인 cms.html이 나타납니다. 사용자가 데이터를 입력하고 저장하면 SQLite 데이터베이스에 저장되고, 메인 페이지(http://localhost:3000/)에서 변경된 데이터를 확인할 수 있습니다.