目錄
問題內容
解決方法
錯誤處理
首頁 後端開發 Golang 嘗試建立新使用者時出現 Golang SQL 錯誤

嘗試建立新使用者時出現 Golang SQL 錯誤

Feb 12, 2024 pm 11:39 PM

尝试创建新用户时出现 Golang SQL 错误

php小編小新在使用Golang建立新使用者時遇到了SQL錯誤的問題。這個錯誤可能會導致用戶無法成功註冊,為網站的正常運作帶來困擾。針對這個問題,我們需要分析錯誤的原因,並找到解決方法。本文將介紹可能導致Golang SQL錯誤的幾個常見原因,並提供相應的解決方案,幫助開發者快速解決這個問題,確保網站的正常運作。

問題內容

使用golang 套件vipercobra 建立使用者時,我在new_user.go 中收到此錯誤。錯誤如下:

cannot use result (variable of type sql.result) as error value in return statement: sql.result does not implement error (missing method error)
登入後複製

我的程式碼被分成兩個相互通信的文件,這是樹層次結構:

.
├── makefile
├── readme.md
├── cli
│   ├── config.go
│   ├── db-creds.yaml
│   ├── go.mod
│   ├── go.sum
│   ├── new_user.go
│   └── root.go
├── docker-compose.yaml
├── go.work
└── main.go
登入後複製

為了連接到資料庫,我建立了一個 yaml 檔案 db-creds.yaml 來提取 config.go 的憑證。這裡沒有彈出錯誤:

config.go 檔案

package cli

import (
    "database/sql"
    "fmt"

    _ "github.com/go-sql-driver/mysql"
    _ "github.com/lib/pq"
    "github.com/spf13/viper"
)

// var dialects = map[string]gorp.dialect{
//  "postgres": gorp.postgresdialect{},
//  "mysql":    gorp.mysqldialect{engine: "innodb", encoding: "utf8"},
// }

// initconfig reads in config file and env variables if set
func initconfig() {
    if cfgfile != "" {
        viper.setconfigfile(cfgfile)
    } else {
        viper.addconfigpath("./")
        viper.setconfigname("db-creds")
        viper.setconfigtype("yaml")
    }

    // if a config file is found, read it in:
    err := viper.readinconfig()
    if err == nil {
        fmt.println("fatal error config file: ", viper.configfileused())
    }
    return
}

func getconnection() *sql.db {

    // make sure we only accept dialects that were compiled in.
    // dialect := viper.getstring("database.dialect")
    // _, exists := dialects[dialect]
    // if !exists {
    //  return nil, "", fmt.errorf("unsupported dialect: %s", dialect)
    // }

    // will want to create another command that will use a mapping
    // to connect to a preset db in the yaml file.
    dsn := fmt.sprintf("%s:%s@%s(%s)?parsetime=true",
        viper.getstring("mysql-5.7-dev.user"),
        viper.getstring("mysql-5.7-dev.password"),
        viper.getstring("mysql-5.7-dev.protocol"),
        viper.getstring("mysql-5.7-dev.address"),
    )
    viper.set("database.datasource", dsn)

    db, err := sql.open("msyql", viper.getstring("database.datasource"))
    if err != nil {
        fmt.errorf("cannot connect to database: %s", err)
    }

    return db
}
登入後複製

我放在頂部的錯誤是當我返回 result 時出現的錯誤。我正在為 cobra 實作 flag 選項,以使用 -n 後面跟著 name 來表示正在新增的使用者。

new_user.go 檔案

package cli

import (
    "log"

    "github.com/sethvargo/go-password/password"
    "github.com/spf13/cobra"
)

var name string

// newCmd represents the new command
var newCmd = &cobra.Command{
    Use:   "new",
    Short: "Create a new a user which will accommodate the individuals user name",
    Long:  `Create a new a user that will randomize a password to the specified user`,
    RunE: func(cmd *cobra.Command, args []string) error {

        db := getConnection()

        superSecretPassword, err := password.Generate(64, 10, 10, false, false)

        result, err := db.Exec("CREATE USER" + name + "'@'%'" + "IDENTIFIED BY" + superSecretPassword)
        if err != nil {
            log.Fatal(err)
        }

        // Will output the secret password combined with the user.
        log.Printf(superSecretPassword)

        return result <---- Error is here
    },
}

func init() {
    rootCmd.AddCommand(newCmd)

    newCmd.Flags().StringVarP(&name, "name", "n", "", "The name of user to be added")
    _ = newCmd.MarkFlagRequired("name")
}
登入後複製

這個專案的主要目的有三點: 1.) 建立一個新用戶, 2.) 授予任何使用者特定權限 3.) 刪除它們。 這就是我的最終目標。一次一步地進行,就遇到了這個錯誤。希望任何人都可以幫助我。 golang 對我來說是個新手,大約兩週前開始使用。

解決方法

go 為您提供了關於正在發生的事情的非常清晰的指示。 cobra 的 rune 成員期望其回呼回傳錯誤(如果成功,則傳回 nil)。

這裡,您回傳的是結果,這不是錯誤,而是 sql 查詢傳回的特定類型。這就是您的函數應該的樣子。

RunE: func(cmd *cobra.Command, args []string) error {

    db := getConnection()

    superSecretPassword, err := password.Generate(64, 10, 10, false, false)

    _, err := db.Exec("CREATE USER" + name + "'@'%'" + "IDENTIFIED BY" + superSecretPassword)
    if err != nil {
        // Don't Fatal uselessly, let cobra handle your error the way it
        // was designed to do it.
        return err
    }

    // Will output the secret password combined with the user.
    log.Printf(superSecretPassword)

    // Here is how you should indicate your callback terminated successfully.
    // Error is an interface, so it accepts nil values.
    return nil
}
登入後複製

如果您需要 db.exec 命令的結果(似乎並非如此),您需要在 cobra 回呼中執行所有必要的處理,因為它不是設計用於將值返回到主執行緒。

錯誤處理

我在程式碼中註意到的一些關於處理錯誤的不良做法:

  • 如果 go 函數傳回錯誤,發生意外情況時不要驚慌或終止程式(就像您對 log.fatal 所做的那樣)。相反,使用該錯誤返回將錯誤傳播到主線程,並讓它決定要做什麼。

  • 另一方面,如果出現問題,請勿傳回結果。如果失敗,您的 getconnection 函數應該可以傳回錯誤:func getconnection() (*sql.db, error)。然後,您應該在 rune 函數中處理此錯誤,而不是只記錄它並正常處理。

以上是嘗試建立新使用者時出現 Golang SQL 錯誤的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1677
14
CakePHP 教程
1431
52
Laravel 教程
1334
25
PHP教程
1279
29
C# 教程
1257
24
Golang vs. Python:性能和可伸縮性 Golang vs. Python:性能和可伸縮性 Apr 19, 2025 am 12:18 AM

Golang在性能和可擴展性方面優於Python。 1)Golang的編譯型特性和高效並發模型使其在高並發場景下表現出色。 2)Python作為解釋型語言,執行速度較慢,但通過工具如Cython可優化性能。

Golang和C:並發與原始速度 Golang和C:並發與原始速度 Apr 21, 2025 am 12:16 AM

Golang在並發性上優於C ,而C 在原始速度上優於Golang。 1)Golang通過goroutine和channel實現高效並發,適合處理大量並發任務。 2)C 通過編譯器優化和標準庫,提供接近硬件的高性能,適合需要極致優化的應用。

開始GO:初學者指南 開始GO:初學者指南 Apr 26, 2025 am 12:21 AM

goisidealforbeginnersandsubableforforcloudnetworkservicesduetoitssimplicity,效率和concurrencyFeatures.1)installgromtheofficialwebsitealwebsiteandverifywith'.2)

Golang vs.C:性能和速度比較 Golang vs.C:性能和速度比較 Apr 21, 2025 am 12:13 AM

Golang適合快速開發和並發場景,C 適用於需要極致性能和低級控制的場景。 1)Golang通過垃圾回收和並發機制提升性能,適合高並發Web服務開發。 2)C 通過手動內存管理和編譯器優化達到極致性能,適用於嵌入式系統開發。

Golang vs. Python:主要差異和相似之處 Golang vs. Python:主要差異和相似之處 Apr 17, 2025 am 12:15 AM

Golang和Python各有优势:Golang适合高性能和并发编程,Python适用于数据科学和Web开发。Golang以其并发模型和高效性能著称,Python则以简洁语法和丰富库生态系统著称。

Golang和C:性能的權衡 Golang和C:性能的權衡 Apr 17, 2025 am 12:18 AM

Golang和C 在性能上的差異主要體現在內存管理、編譯優化和運行時效率等方面。 1)Golang的垃圾回收機制方便但可能影響性能,2)C 的手動內存管理和編譯器優化在遞歸計算中表現更為高效。

表演競賽:Golang vs.C 表演競賽:Golang vs.C Apr 16, 2025 am 12:07 AM

Golang和C 在性能競賽中的表現各有優勢:1)Golang適合高並發和快速開發,2)C 提供更高性能和細粒度控制。選擇應基於項目需求和團隊技術棧。

Golang vs. Python:利弊 Golang vs. Python:利弊 Apr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

See all articles