亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我可以使用 Go 連接到 Memgraph 嗎?

我可以使用 Go 連接到 Memgraph 嗎?

Go
烙印99 2023-03-15 14:52:28
我想從 Go 連接到 Memgraph 數據庫的運行實例。我正在使用 Docker 并安裝了 Memgraph 平臺。我到底需要做什么?
查看完整描述

1 回答

?
紫衣仙女

TA貢獻1839條經驗 獲得超15個贊

從 Go 連接到 Memgraph 的過程相當簡單。為此,您需要使用 Bolt 協議。以下是所需的步驟:


首先,為您的應用程序創建一個新目錄,/MyApp并將您自己定位在其中。program.go接下來,使用以下代碼創建一個文件:


package main


import (

? ? "fmt"


? ? "github.com/neo4j/neo4j-go-driver/v4/neo4j"

)


func main() {

? ? dbUri := "bolt://localhost:7687"

? ? driver, err := neo4j.NewDriver(dbUri, neo4j.BasicAuth("username", "password", ""))

? ? if err != nil {

? ? ? ? panic(err)

? ? }

? ? // Handle driver lifetime based on your application lifetime requirements? driver's lifetime is usually

? ? // bound by the application lifetime, which usually implies one driver instance per application

? ? defer driver.Close()

? ? item, err := insertItem(driver)

? ? if err != nil {

? ? ? ? panic(err)

? ? }

? ? fmt.Printf("%v\n", item.Message)

}


func insertItem(driver neo4j.Driver) (*Item, error) {

? ? // Sessions are short-lived, cheap to create and NOT thread safe. Typically create one or more sessions

? ? // per request in your web application. Make sure to call Close on the session when done.

? ? // For multi-database support, set sessionConfig.DatabaseName to requested database

? ? // Session config will default to write mode, if only reads are to be used configure session for

? ? // read mode.

? ? session := driver.NewSession(neo4j.SessionConfig{})

? ? defer session.Close()

? ? result, err := session.WriteTransaction(createItemFn)

? ? if err != nil {

? ? ? ? return nil, err

? ? }

? ? return result.(*Item), nil

}


func createItemFn(tx neo4j.Transaction) (interface{}, error) {

? ? records, err := tx.Run(

? ? ? ? "CREATE (a:Greeting) SET a.message = $message RETURN 'Node ' + id(a) + ': ' + a.message",

? ? ? ? map[string]interface{}{"message": "Hello, World!"})

? ? // In face of driver native errors, make sure to return them directly.

? ? // Depending on the error, the driver may try to execute the function again.

? ? if err != nil {

? ? ? ? return nil, err

? ? }

? ? record, err := records.Single()

? ? if err != nil {

? ? ? ? return nil, err

? ? }

? ? // You can also retrieve values by name, with e.g. `id, found := record.Get("n.id")`

? ? return &Item{

? ? ? ? Message: record.Values[0].(string),

? ? }, nil

}


type Item struct {

? ? Message string

}

現在,go.mod使用go mod init example.com/hello命令創建一個文件。我之前提到過 Bolt 驅動器。您需要添加它go get github.com/neo4j/neo4j-go-driver/[email protected]。你可以運行你的程序go run .\program.go。



查看完整回答
反對 回復 2023-03-15
  • 1 回答
  • 0 關注
  • 92 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號