Skip to content

Examples

JulienSchmidt edited this page Jan 25, 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 a, b, c FROM table")
	if err != nil {
		panic(err.Error())
	}

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

	// Fetch rows
	var a, b, c sql.RawBytes
	for rows.Next() {
		// get RawBytes from data
		err = rows.Scan(&a, &b, &c)
		if err != nil {
			panic(err.Error())
		}

		// Now do something with the data. Here we just print it as a string.
		// Since RawBytes might be nil, we must check this before converting to string:
		if a == nil {
			fmt.Print(nil)
		} else {
			fmt.Print(string(a))
		}
		fmt.Print(` | `)
		if b == nil {
			fmt.Print(nil)
		} else {
			fmt.Print(string(b))
		}
		fmt.Print(` | `)
		if c == nil {
			fmt.Print(nil)
		} else {
			fmt.Print(string(c))
		}
		fmt.Println()
	}
}

Feel free to contribute your own examples!

Clone this wiki locally