How to fetch multiple column from mysql using go lang

huangapple go评论76阅读模式
英文:

How to fetch multiple column from mysql using go lang

问题

我正在尝试使用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, "第一个的标题是:"+first+",第二个是:"+second)
}
conn.Close()

以上是你提供的代码的翻译。

英文:

I am trying to fetch multiple columns in a mysql database using the go language. Currently I could modify this script, and it would work perfectly well for just fetching one column, and printing it using the http print function. However, when it fetches two things the script no longer works. I don't have any idea what I need to do to fix it. I know that the sql is fine as I have tested that out in the mysql terminal, and it has given me the expected result that I wanted.

 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()

答案1

得分: 3

你正在使用错误的变量名,但我假设这只是你示例代码中的一个“拼写错误”。

然后,正确的语法是:

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

关于Scan(dest ...interface{})的含义和用法,请参考这里

你还应该处理错误,而不是忽略它们。

最后,你应该使用Fprintf,因为它是用来这样使用的:

fmt.Fprintf(w, "第一个的标题是:%s\n第二个是:%s", first, second)
英文:

You are using the wrong variable names but I assume that's just a "typo" in your sample code.

Then the correct syntax is:

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

See this on what Scan(dest ...interface{}) means and how to use it.

You should also handle and not ignore the errors.

Finally, you should use Fprintf as it's intended:

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

huangapple
  • 本文由 发表于 2015年7月2日 14:12:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/31176777.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定