dov11020 2015-07-02 06:12
浏览 132
已采纳

如何使用Go lang从mysql获取多列

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条回答 默认 最新

  • doudao1282 2015-07-02 06:34
    关注

    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
    The second is: %s", first, second)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效