Created
September 23, 2015 15:14
-
-
Save apremalal/477509c9ce8e0b9c9c1c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"os" | |
"database/sql" | |
"gopkg.in/gorp.v1" | |
"log" | |
_ "github.com/go-sql-driver/mysql" | |
) | |
func main() { | |
// initialize the DbMap | |
dbmap := initDb() | |
defer dbmap.Db.Close() | |
// fetch all rows | |
var posts []User | |
_, err := dbmap.Select(&posts, "select username from radcheck order by id") | |
checkErr(err, "Select failed") | |
log.Println("All rows:") | |
for x := range posts { | |
json.NewEncoder(os.Stdout).Encode(posts[x]) | |
//log.Printf(" %d: %v\n", x, p) | |
} | |
//json.NewEncoder(os.Stdout).Encode(message) | |
log.Println("Done!") | |
} | |
type User struct { | |
// db tag lets you specify the column name if it differs from the struct field | |
Id int64 `db:"id"` | |
Username string `db:"username"json:"username"` // Column size set to 50 | |
Value string `db:"value"` // Set both column name and size | |
} | |
func initDb() *gorp.DbMap { | |
// connect to db using standard Go database/sql API | |
// use whatever database/sql driver you wish | |
var connectionUrl = "root:root@tcp(localhost:3306)/radius_tmp" | |
db, err := sql.Open("mysql", connectionUrl) | |
checkErr(err, "sql.Open failed") | |
// construct a gorp DbMap | |
dbmap := &gorp.DbMap{Db: db, Dialect:gorp.MySQLDialect{"InnoDB", "UTF8"}} | |
checkErr(err, "Create tables failed") | |
return dbmap | |
} | |
func checkErr(err error, msg string) { | |
if err != nil { | |
log.Fatalln(msg, err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment