sqlite - 如何在 Next.js 中更正 SQLite“没有这样的表”?
问题描述
我正在研究 Next.js,当我尝试从 SQLite3 数据库中预取数据时,遇到了“SQLITE_ERROR: no such table: post”错误。我确定该表存在,我已经运行了一个查询以确定它确实返回了预期的结果。我能想到的唯一其他可能性是我没有正确引用我的数据库。我正在使用 Knex 连接它。
这是我的代码:
数据库/index.js:
import knex from "knex"
import path from "path"
const database = knex({
client: "sqlite3",
connection: {
filename: path.resolve(__dirname, "database.sqlite")
},
useNullAsDefault: true
})
export default database
库/posts.js:
import database from "../database"
export const getAllPostsIds = async () => {
try {
let fileNames = await database.select("title").from("post")
return fileNames.map(fileName => {
{
params: {
id: fileName
}
}
})
} catch (error) {
return {
params: {
id: "error: " + error
}
}
}
}
函数调用(pages/index.js):
import Head from "next/head"
import Layout from "../components/layout"
import { getAllPostsIds } from "../lib/posts"
export default function Home({ data }) {
return (
<Layout>
<Head>
<title>Home</title>
</Head>
<section></section>
</Layout>
)
}
export const getStaticProps = async ({ params }) => {
const data = await getAllPostsIds()
return {
props: {
data
}
}
}
相关的树结构:
|components
|--|layout
|--|--index.js
|database
|--|index.js
|lib
|--|posts.js
|pages
|--|index.js
错误:
{
params: {
id: 'error: Error: select `title` from `post` - SQLITE_ERROR: no such table: post'
}
}
解决方案
尝试这个:
您不能使用 __dirname 因为它将返回的路径将与 pages 目录不同。相反,您可以使用
process.cwd()
which 为您提供执行 Next.js 的目录。
import knex from "knex"
import path from "path"
// Add this line
const __dirname = path.resolve()
const database = knex({
client: "sqlite3",
connection: {
filename: path.resolve(__dirname, "database.sqlite") // or -> path.join(process.cwd(), "database.sqlite")
},
useNullAsDefault: true
})
export default database
推荐阅读
- conditional-statements - 当 nls 适合时 tryCatch 崩溃
- c - 如何从 USB 设备名称中获取 USB 端口?
- calculator - 如何在 python 中显示下面的整个根多项式?
- c# - 任何一个键都可以为空的多键字典
- c# - 停止 VSCode 格式化在保存时执行特定的格式化(换行符)
- python - 如何验证电话号码前缀
- python - Dataframe groupby 对不同的列使用不同的函数
- postgresql - PostgresSQL 中的参数嗅探/绑定窥视
- python - /create/ NOT NULL 约束处的 IntegrityError 失败:main_post.author_id
- android - 未从 recyclerview 获取总项目数