【问题标题】:How to fetch multiple column from mysql using go lang如何使用 go lang 从 mysql 中获取多列
【发布时间】:2015-09-19 12:32:51
【问题描述】:

我正在尝试使用 go 语言获取 mysql 数据库中的多个列。目前我可以修改这个脚本,它可以很好地获取一列,并使用 http 打印功能打印它。但是,当它获取两件事时,脚本不再起作用。我不知道我需要做什么来修复它。我知道 sql 很好,因为我已经在 mysql 终端中对其进行了测试,它给了我想要的预期结果。

 conn, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/database")
 statement, err := conn.Prepare("select first,second from table") 
 rows, err := statement.Query()
 for rows.Next() {
         var first string
         rows.Scan(&first)
         var second string
         rows.Scan(&second)
         fmt.Fprintf(w, "Title of first is :"+first+"The second is"+second)
 }
 conn.Close()

【问题讨论】:

  • 什么是“http打印功能”?

标签: mysql web go


【解决方案1】:

您使用了错误的变量名,但我认为这只是您的示例代码中的“错字”。

那么正确的语法是:

var first, second string
rows.Scan(&first, &second)

请参阅this,了解Scan(dest ...interface{}) 的含义以及如何使用它。

您还应该处理而不是忽略错误。

最后,您应该按照预期使用Fprintf

fmt.Fprintf(w, "Title of first is : %s\nThe second is: %s", first, second)

【讨论】:

  • 参见golang.org/pkg/fmt - 它们是格式说明符,对大多数基于 C 的语言都很常见。
猜你喜欢
  • 2012-06-20
  • 2020-12-27
  • 1970-01-01
  • 2015-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-20
  • 2020-08-23
相关资源
最近更新 更多