首页 > 解决方案 > 如何在 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'
  }
}

标签: sqlitenext.jsknex.js

解决方案


尝试这个:

您不能使用 __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

推荐阅读