Skip to content
Nirbhay Choubey edited this page Jan 16, 2016 · 3 revisions

Opening a connection

dsn = "mysql://user:pass@localhost:3306/test"

if db, err = sql.Open("vaquita", dsn); err != nil {
        fmt.Println("sql.Open() failed : ", err)
} else if err = db.Ping(); err != nil {
        fmt.Println("db.Ping() failed : ", err)
        os.Exit(1)
} else {
        fmt.Println("Connection established successfully")
}

Executing queries

var (
        err             error
        db              *sql.DB
        result          sql.Result
        rows            *sql.Rows
        // ..snip..
)

// ..snip..
if result, err = db.Exec("create table %s (i int, j varchar(20))", "test.t1"); err != nil {
        fmt.Println("Db.Exec() failed : ", err)
}

// ..snip..
if result, err = db.Exec("insert into test.t1 values (?, ?)", 1, "NULL"); err != nil {
        fmt.Println("Db.Exec() failed : ", err)
}

// ..snip..
if rows, err = db.Query("select * from test.t1"); err != nil {
        fmt.Println("Db.Query() failed : ", err)
}

// ..snip..

Inspecting Exec() result (sql.Result)

lastInsertId, _ := result.LastInsertId()
rowsAffected, _ := result.RowsAffected()

Inspecting Query() rows (sql.Rows)

defer rows.Close()
// ...
for rows.Next() {
        var (
                i int
                s sql.NullString
        )
        if err = rows.Scan(&i, &s); err != nil {
                fmt.Println("Rows.Scan failed : ", err)
        } else {
                fmt.Println("Row : ", i, s)
        }
}

Prepared statements

var stmt *sql.Stmt

// ..snip..
// Prepare
if stmt, err = db.Prepare("select * from test.t1 where i = ?"); err != nil {
        fmt.Println("Db.Prepare() failed : ", err)
        os.Exit(1)
}

// Execute
if rows, err = stmt.Query(1); err != nil {
        fmt.Println("Stmt.Query() failed : ", err)
} else {
        // Process rows
}

// close
if err = stmt.Close(); err != nil {
        fmt.Println("Stmt.Close() failed : ", err)
        os.Exit(1)
}