Next.js項目中使用SQLite的實現(xiàn)示例
無論你是做一個MVP,還是完整的 Web 應用,存儲和讀取數(shù)據(jù)都至關重要。SQLite 是一款可移植、零配置的輕型數(shù)據(jù)庫,能讓你快速上手。
1. 為什么要在 Next.js 中使用 SQLite?
- Next.js 是構(gòu)建服務端器 React 框架,自動處理路由、SSR、代碼分割等。
- SQLite 是一款文件型 SQL 數(shù)據(jù)庫引擎,輕量、快速且零配置。
Next.js + SQLite 的優(yōu)勢:
- 簡單設置:SQLite 只是普通文件存儲,無需運行復雜的數(shù)據(jù)庫服務器。
- 客戶端查詢:可直接在 Next.js 應用中執(zhí)行查詢,無需額外后端。
- 離線持久化:用戶短暫離線后數(shù)據(jù)依然存在。
- 可移植性:數(shù)據(jù)庫文件可在不同環(huán)境與平臺間輕松遷移。
- 可擴展性:SQLite 足夠應付大多數(shù)簡單查詢需求,后期可平滑遷移到 Postgres、MySQL 等。
在快速原型階段,SQLite 讓你無需搭建獨立數(shù)據(jù)庫服務器即可驗證核心功能。
2. 安裝依賴
在 Next.js 中使用 SQLite,需安裝以下依賴:
npm install sqlite3 npm install @mapbox/node-sqlite3 npm install sqlite
3. 創(chuàng)建數(shù)據(jù)庫
在 pages/api 目錄下新建 db.js:
// pages/api/db.js
import sqlite3 from 'sqlite3'
import { open } from 'sqlite'
// 打開 SQLite 數(shù)據(jù)庫連接
export async function openDb() {
return open({
filename: './mydb.db',
driver: sqlite3.Database
})
}
該文件會在項目根目錄創(chuàng)建名為 mydb.db 的 SQLite 文件。若文件不存在,首次連接時會自動創(chuàng)建。
4. 定義表結(jié)構(gòu)
在 pages/api 目錄下創(chuàng)建 seed.js,用于初始化數(shù)據(jù)庫表:
// pages/api/seed.js
import { openDb } from './db'
async function setup() {
const db = await openDb()
// 創(chuàng)建 posts 表
await db.exec(`
CREATE TABLE posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
content TEXT
);
`)
// 插入示例數(shù)據(jù)
await db.run(
'INSERT INTO posts (title, content) VALUES (?, ?)',
'Hello World',
'My first blog post!'
)
await db.close()
}
setup().catch(err => console.error(err.message))
運行腳本:
node pages/api/seed.js
至此,數(shù)據(jù)庫與表已準備就緒。
5. 獲取數(shù)據(jù)(服務端渲染)
在 pages/index.js 中利用 getServerSideProps 查詢數(shù)據(jù)并傳給組件:
// pages/index.js
import { openDb } from './api/db'
export async function getServerSideProps() {
const db = await openDb()
const posts = await db.all('SELECT * FROM posts')
await db.close()
return {
props: { posts }
}
}
function Home({ posts }) {
// 在 UI 中渲染 posts
return (
<div>
<h1>Posts</h1>
<ul>
{posts.map(p => (
<li key={p.id}>
<h2>{p.title}</h2>
<p>{p.content}</p>
</li>
))}
</ul>
</div>
)
}
export default Home
6. 實現(xiàn) CRUD 操作
6.1 創(chuàng)建(Create)
pages/api/posts/create.js:
import { openDb } from '../db'
export default async function handler(req, res) {
const { title, content } = req.body
const db = await openDb()
const result = await db.run(
'INSERT INTO posts (title, content) VALUES (?, ?)',
[title, content]
)
await db.close()
res.status(201).json(result)
}
6.2 讀?。≧ead)
pages/api/posts/[id].js:
import { openDb } from '../../db'
export default async function handler(req, res) {
const id = req.query.id
const db = await openDb()
const post = await db.get('SELECT * FROM posts WHERE id = ?', [id])
await db.close()
res.status(200).json(post)
}
6.3 更新(Update)
pages/api/posts/update.js:
import { openDb } from '../db'
export default async function handler(req, res) {
const { id, title, content } = req.body
const db = await openDb()
await db.run(
`UPDATE posts SET title = ?, content = ? WHERE id = ?`,
[title, content, id]
)
await db.close()
res.status(200).json({ message: 'Post updated' })
}
6.4 刪除(Delete)
pages/api/posts/delete.js:
import { openDb } from '../db'
export default async function handler(req, res) {
const { id } = req.body
const db = await openDb()
await db.run('DELETE FROM posts WHERE id = ?', [id])
await db.close()
res.status(200).json({ message: 'Post deleted' })
}
7. 客戶端數(shù)據(jù)獲?。⊿WR/React Query)
暴露統(tǒng)一的 /api/posts 端點:
// pages/api/posts.js
import { openDb } from './db'
export default async function handler(req, res) {
const db = await openDb()
const posts = await db.all('SELECT * FROM posts')
await db.close()
res.status(200).json(posts)
}
在客戶端組件中:
useEffect(() => {
async function fetchPosts() {
const res = await fetch('/api/posts')
const posts = await res.json()
// 更新組件狀態(tài)
}
fetchPosts()
}, [])
到此這篇關于Next.js項目中使用SQLite的實現(xiàn)示例的文章就介紹到這了,更多相關Next.js使用SQLite內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
javascript下有關dom以及xml節(jié)點訪問兼容問題
javascript下有關dom以及xml節(jié)點訪問兼容問題...2007-11-11
JavaScript實現(xiàn)微信小程序打卡時鐘項目實例
這篇文章主要為大家介紹了JavaScript實現(xiàn)微信小程序打卡時鐘項目實例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-04-04
JavaScript中常見的數(shù)據(jù)格式化方式詳解
這篇文章主要為大家詳細介紹了JavaScript中常見的數(shù)據(jù)格式化方式,文中的示例代碼講解詳細,具有一定的借鑒價值,感興趣的小伙伴可以了解一下2023-12-12

