matt
matt

Reputation: 337

How to fetch multiple column from mysql using go lang

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

Upvotes: 1

Views: 4440

Answers (1)

IamNaN
IamNaN

Reputation: 6864

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)

Upvotes: 3

Related Questions