Saturday, May 30, 2015

Day 13 - Howto use gorp select

The dbmap.Select function in gorp can be used in two different ways. .



    // Method 1: Results are returned as an array 
    // of interfaces ( = rows here )
    rows, err := dbmap.Select(foo, "select * from " + table.TableName)

    // Method 1: read the rows from the returned array of interfaces  
    // rows := []interface{}
    for _, row := range rows {
        // cast the row to our struct
        af := row.(*AliasTransientField)
        fmt.Printf("Method1: ID: %d, BarStr: %s\n", af.GetId(), af.BarStr)
    }


    // Method 2: Resulting rows are appended to a pointer of a slice (foos)
    var foos []AliasTransientField
    _, err = dbmap.Select(&foos, "select * from " + table.TableName)

    // Method 2: read the rows from the input slice (=foos)
    for _, f := range foos {
        fmt.Printf("Method2: ID: %d, BarStr: %s\n", f.Id, f.BarStr)
    }

I needed some time to figure this out (especially the cast) and I hope it can be useful to somebody.

The full code for this test is in: https://github.com/kimxilxyong/intogooglego/tree/master/testgorp


No comments:

Post a Comment