英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论