求助:Golang数据库集成遇到问题如何解决

求助:Golang数据库集成遇到问题如何解决 有没有人在GoLand和Fiber项目中使用过Prisma客户端来与数据库交互?如果有的话,能否分享一下安装过程是如何进行的,以及你是如何在Prisma模式文件中组织数据的?

2 回复

嘿,我对这方面了解不多——但也许你可以试试用 GoFr。

GoFr - An opinionated Go Framework

GoFr - 一个固执己见的 Go 框架

用于加速微服务开发

我们支持很多数据库,你可以为此创建一个 issue,这样你只需要提供配置来连接,类似于这份文档中的这些。

更多关于求助:Golang数据库集成遇到问题如何解决的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在GoLand和Fiber项目中使用Prisma客户端与数据库交互,可以通过以下步骤实现:

  1. 安装Prisma CLI
npm install -g prisma
# 或使用yarn
yarn global add prisma
  1. 初始化Prisma
prisma init
  1. 配置数据库连接(在.env文件中):
DATABASE_URL="postgresql://user:password@localhost:5432/mydb"
  1. 定义数据模型(在prisma/schema.prisma中):
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model User {
  id        Int      @id @default(autoincrement())
  email     String   @unique
  name      String?
  posts     Post[]
  createdAt DateTime @default(now())
}

model Post {
  id        Int      @id @default(autoincrement())
  title     String
  content   String?
  published Boolean  @default(false)
  author    User     @relation(fields: [authorId], references: [id])
  authorId  Int
}
  1. 生成Prisma客户端
prisma generate
  1. 在Go中通过子进程调用Prisma客户端
package main

import (
    "encoding/json"
    "fmt"
    "os/exec"
)

type User struct {
    ID    int    `json:"id"`
    Email string `json:"email"`
    Name  string `json:"name"`
}

func main() {
    // 通过Node.js执行Prisma查询
    cmd := exec.Command("node", "-e", `
        const { PrismaClient } = require('@prisma/client')
        const prisma = new PrismaClient()
        
        async function main() {
            const users = await prisma.user.findMany()
            console.log(JSON.stringify(users))
        }
        
        main()
            .catch(console.error)
            .finally(() => prisma.$disconnect())
    `)
    
    output, err := cmd.Output()
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    
    var users []User
    json.Unmarshal(output, &users)
    fmt.Printf("Users: %+v\n", users)
}
  1. 在Fiber路由中使用
package main

import (
    "encoding/json"
    "github.com/gofiber/fiber/v2"
    "os/exec"
)

func main() {
    app := fiber.New()
    
    app.Get("/users", func(c *fiber.Ctx) error {
        cmd := exec.Command("node", "-e", `
            const { PrismaClient } = require('@prisma/client')
            const prisma = new PrismaClient()
            
            async function main() {
                return await prisma.user.findMany({
                    include: { posts: true }
                })
            }
            
            main()
                .then(console.log)
                .catch(console.error)
                .finally(() => prisma.$disconnect())
        `)
        
        output, err := cmd.Output()
        if err != nil {
            return c.Status(500).SendString(err.Error())
        }
        
        return c.Type("json").Send(output)
    })
    
    app.Listen(":3000")
}
  1. 使用Go的Prisma客户端替代方案
# 安装Prisma Go客户端
go get github.com/prisma/prisma-client-go
package main

import (
    "context"
    "fmt"
    "github.com/prisma/prisma-client-go/runtime"
)

func main() {
    client := runtime.NewClient()
    ctx := context.Background()
    
    // 创建用户
    user, err := client.User.CreateOne(
        runtime.User.Email.Set("test@example.com"),
        runtime.User.Name.Set("Test User"),
    ).Exec(ctx)
    
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    
    fmt.Printf("Created user: %+v\n", user)
}

这种集成方式允许在Go项目中利用Prisma的强大功能,同时保持Go的性能优势。

回到顶部