Golang SQL 错误:创建新用户失败的尝试
来源:stackoverflow
时间:2024-02-09 12:36:26 199浏览 收藏
IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《Golang SQL 错误:创建新用户失败的尝试》,聊聊,我们一起来看看吧!
使用 golang 包 viper
和 cobra
创建用户时,我在 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 错误:创建新用户失败的尝试》的详细内容,更多关于的资料请关注golang学习网公众号!
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
139 收藏
-
204 收藏
-
325 收藏
-
477 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习