Ani*_*rai 5 sqlite node.js better-sqlite3 sveltekit
我一直在将 sqlite3 用于我的大部分全栈应用程序(前端的 node/express、django/drf + svelte 作为 api 端点的使用者),并且一直在试图弄清楚如何集成 sqlite3。
这是我所做的
我假设您熟悉 sveltekit。对于那些新手,你可以去看看SvelteKit
database.js在src/lib文件夹内创建文件import sqlite from 'better-sqlite3'
const DB = new sqlite('./annadb.sqlite')
const schema = `CREATE TABLE IF NOT EXISTS posts(
id INTEGER NOT NULL PRIMARY KEY,
title TEXT NOT NULL
)`;
DB.exec(schema)
export default DB
Run Code Online (Sandbox Code Playgroud)
index.json.js端点以src/routes使用以下代码从文件夹内的数据库中获取所有文章:import DB from '$lib/database.js'
export async function get() {
const articles = await DB.prepare('SELECT * FROM posts').all()
if (articles) {
return {
body: {
articles
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
<script context="module">
export async function load({ fetch }) {
const res = await fetch(/index.json);
if (res.ok) {
return {
props: {
articles: await res.json(),
},
};
}
return {
status: res.status,
error: new Error("Could not load"),
};
}
</script>
Run Code Online (Sandbox Code Playgroud)
<script>
export let articles;
let latestArticles = articles.articles;
console.log(articles);
</script>
<main>
{#if latestArticles.length > 0}
{#each latestArticles as article}
<h2>{article.title}</h2>
{/each}
{:else}
<p>Articles are coming soon</p>
{/if}
</main>
Run Code Online (Sandbox Code Playgroud)
就是这样。
| 归档时间: |
|
| 查看次数: |
782 次 |
| 最近记录: |