Go语言支持哪些数据库?
2024-05-16

package main

import (
    "context"
    "fmt"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
    client, err := mongo.Connect(context.Background(), clientOptions)
    if err != nil {
        panic(err.Error())
    }
    defer client.Disconnect(context.Background())

    collection := client.Database("test").Collection("users")

    // 插入数据
    _, err = collection.InsertOne(context.Background(), bson.D{
        {"name", "Alice"},
        {"age", 30},
    })
    if err != nil {
        panic(err.Error())
    }

    // 查询数据
    cursor, err := collection.Find(context.Background(), bson.D{})
    if err != nil {
        panic(err.Error())
    }
    defer cursor.Close(context.Background())

    for cursor.Next(context.Background()) {
        var result bson.M
        err := cursor.Decode(&result)
        if err != nil {
            panic(err.Error())
        }
        fmt.Println(result)
    }
}
登录后复制