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

2024年 2月 13日 37.7k 0

尝试创建新用户时出现 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 登录后复制

这个项目的主要目的有三点:
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 错误的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论