Skip to content

Examples

ahormann edited this page Jan 26, 2013 · 39 revisions
package main

import (
	"database/sql"
	"fmt"
	_ "github.com/Go-SQL-Driver/MySQL"
)

func main() {
	// Open database connection
	db, err := sql.Open("mysql", "user:password@/dbname?charset=utf8")
	if err != nil {
		panic(err)
	}
	defer db.Close()

	// Execute the query
	rows, err := db.Query("SELECT * FROM table LIMIT 2")
	if err != nil {
		panic(err.Error())
	}

	// Get column names
	columns, err := rows.Columns()
	if err != nil {
		panic(err.Error())
	}

	// we Scan the values into cols
	cols := make([]sql.RawBytes, len(columns))
	// but Scan uses interface{}, so we first store the references to cols
	readCols := make([]interface{}, len(columns))
	for i, _ := range cols {
		readCols[i] = &cols[i]
	}

	// Fetch rows
	for rows.Next() {
		// get RawBytes from data
		err = rows.Scan(readCols...)
		if err != nil {
			panic(err.Error())
		}

		// Now do something with the data. Here we just print each column as a string.
		for i, col := range cols {
			// Since RawBytes might be nil, we must check this before converting to string:
			var value string
			if col == nil {
				value = "NULL"
			} else {
				value = string(col)
			}
			fmt.Println(columns[i], ":\t", value)
		}
		fmt.Println("-----------------------------------")
	}
}

Feel free to contribute your own examples!

Clone this wiki locally