Use method DB() to get database connection handle

This commit is contained in:
Jinzhu 2013-12-04 14:29:44 +08:00
parent a0ac9992cd
commit 90a4581a7f
3 changed files with 13 additions and 6 deletions

View File

@ -76,10 +76,13 @@ db, err := Open("postgres", "user=gorm dbname=gorm sslmode=disable")
// db, err = Open("mysql", "gorm:gorm@/gorm?charset=utf8&parseTime=True") // db, err = Open("mysql", "gorm:gorm@/gorm?charset=utf8&parseTime=True")
// db, err = Open("sqlite3", "/tmp/gorm.db") // db, err = Open("sqlite3", "/tmp/gorm.db")
// Get database connection handle [*sql.DB](http://golang.org/pkg/database/sql/#DB)
d := db.DB()
// Set the maximum idle database connections // With it you could use package `database/sql`'s builtin methods
db.SetPool(100) db.DB().SetMaxIdleConns(10)
db.DB().SetMaxOpenConns(100)
db.DB().Ping()
// By default, table name is plural of struct type, you can use struct type as table name with: // By default, table name is plural of struct type, you can use struct type as table name with:
db.SingularTable(true) db.SingularTable(true)

View File

@ -91,7 +91,7 @@ func init() {
// CREATE DATABASE 'gorm'; // CREATE DATABASE 'gorm';
// GRANT ALL ON gorm.* TO 'gorm'@'localhost'; // GRANT ALL ON gorm.* TO 'gorm'@'localhost';
fmt.Println("testing mysql...") fmt.Println("testing mysql...")
db, err = Open("mysql", "gorm:gorm@/gorm?charset=utf8&parseTime=True") db, err = Open("mysql", "gorm:gorm@/gorim?charset=utf8&parseTime=True")
case "sqlite": case "sqlite":
fmt.Println("testing sqlite3...") fmt.Println("testing sqlite3...")
db, err = Open("sqlite3", "/tmp/gorm.db") db, err = Open("sqlite3", "/tmp/gorm.db")
@ -101,12 +101,11 @@ func init() {
} }
// db.SetLogger(log.New(os.Stdout, "\r\n", 0)) // db.SetLogger(log.New(os.Stdout, "\r\n", 0))
// db.LogMode(true) // db.LogMode(true)
if err != nil { if err != nil {
panic(fmt.Sprintf("No error should happen when connect database, but got %+v", err)) panic(fmt.Sprintf("No error should happen when connect database, but got %+v", err))
} }
db.SetPool(10) db.DB().SetMaxIdleConns(10)
if err := db.DropTable(&User{}).Error; err != nil { if err := db.DropTable(&User{}).Error; err != nil {
fmt.Printf("Got error when try to delete table users, %+v\n", err) fmt.Printf("Got error when try to delete table users, %+v\n", err)

View File

@ -2,6 +2,7 @@ package gorm
import ( import (
"database/sql" "database/sql"
"github.com/jinzhu/gorm/dialect" "github.com/jinzhu/gorm/dialect"
) )
@ -26,6 +27,10 @@ func Open(driver, source string) (db DB, err error) {
return return
} }
func (s *DB) DB() *sql.DB {
return s.db.(*sql.DB)
}
func (s *DB) SetPool(n int) { func (s *DB) SetPool(n int) {
if db, ok := s.parent.db.(sqlDb); ok { if db, ok := s.parent.db.(sqlDb); ok {
db.SetMaxIdleConns(n) db.SetMaxIdleConns(n)