Golang SQL 错误:创建新用户失败的尝试
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学习网公众号!

- 上一篇
- 如何调整 GoLand 自动生成测试时默认使用的消息结构

- 下一篇
- 如何更改mac的无线网络密码?
-
- Golang · Go问答 | 1年前 |
- 在读取缓冲通道中的内容之前退出
- 139浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 戈兰岛的全球 GOPRIVATE 设置
- 204浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将结构作为参数传递给 xml-rpc
- 325浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何用golang获得小数点以下两位长度?
- 477浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何通过 client-go 和 golang 检索 Kubernetes 指标
- 486浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将多个“参数”映射到单个可变参数的习惯用法
- 439浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将 HTTP 响应正文写入文件后出现 EOF 错误
- 357浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 结构中映射的匿名列表的“复合文字中缺少类型”
- 352浏览 收藏
-
- Golang · Go问答 | 1年前 |
- NATS Jetstream 的性能
- 101浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将复杂的字符串输入转换为mapstring?
- 440浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 相当于GoLang中Java将Object作为方法参数传递
- 212浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何确保所有 goroutine 在没有 time.Sleep 的情况下终止?
- 143浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- 笔灵AI生成答辩PPT
- 探索笔灵AI生成答辩PPT的强大功能,快速制作高质量答辩PPT。精准内容提取、多样模板匹配、数据可视化、配套自述稿生成,让您的学术和职场展示更加专业与高效。
- 24次使用
-
- 知网AIGC检测服务系统
- 知网AIGC检测服务系统,专注于检测学术文本中的疑似AI生成内容。依托知网海量高质量文献资源,结合先进的“知识增强AIGC检测技术”,系统能够从语言模式和语义逻辑两方面精准识别AI生成内容,适用于学术研究、教育和企业领域,确保文本的真实性和原创性。
- 38次使用
-
- AIGC检测-Aibiye
- AIbiye官网推出的AIGC检测服务,专注于检测ChatGPT、Gemini、Claude等AIGC工具生成的文本,帮助用户确保论文的原创性和学术规范。支持txt和doc(x)格式,检测范围为论文正文,提供高准确性和便捷的用户体验。
- 37次使用
-
- 易笔AI论文
- 易笔AI论文平台提供自动写作、格式校对、查重检测等功能,支持多种学术领域的论文生成。价格优惠,界面友好,操作简便,适用于学术研究者、学生及论文辅导机构。
- 48次使用
-
- 笔启AI论文写作平台
- 笔启AI论文写作平台提供多类型论文生成服务,支持多语言写作,满足学术研究者、学生和职场人士的需求。平台采用AI 4.0版本,确保论文质量和原创性,并提供查重保障和隐私保护。
- 41次使用
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- Golang取得代码运行时间的问题
- 2023-02-24 501浏览
-
- 请问 go 代码如何实现在代码改动后不需要Ctrl+c,然后重新 go run *.go 文件?
- 2023-01-08 501浏览
-
- 如何从同一个 io.Reader 读取多次
- 2023-04-11 501浏览