gorm/doc/database/connect-database.md

67 lines
1.2 KiB
Markdown
Raw Normal View History

2016-02-21 18:09:24 +03:00
# Database Connection
<!-- toc -->
## Connecting to a database
#### MySQL
**NOTE** don't forgot params `parseTime` to handle data type `time.Time`, [more support parameters](https://github.com/go-sql-driver/mysql#parameters)
2016-02-21 16:42:26 +03:00
```go
import (
"github.com/jinzhu/gorm"
_ "github.com/go-sql-driver/mysql"
)
2016-02-21 18:09:24 +03:00
func main() {
db, err := gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local")
}
```
2016-02-21 16:42:26 +03:00
2016-02-21 18:09:24 +03:00
#### PostgreSQL
```go
import (
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
)
func main() {
2016-02-21 16:42:26 +03:00
db, err := gorm.Open("postgres", "user=gorm dbname=gorm sslmode=disable")
2016-02-21 18:09:24 +03:00
}
```
#### Sqlite3
2016-02-21 16:42:26 +03:00
2016-02-21 18:09:24 +03:00
```go
import (
"github.com/jinzhu/gorm"
_ "github.com/mattn/go-sqlite3"
)
func main() {
db, err := gorm.Open("sqlite3", "/tmp/gorm.db")
2016-02-21 16:42:26 +03:00
}
```
2016-02-21 18:09:24 +03:00
#### Write Dialect for unsupported databases
GORM officially support above databases, for unsupported databaes, you could write a dialect for that.
Refer: https://github.com/jinzhu/gorm/blob/master/dialect.go
## Generic database object *sql.DB
[*sql.DB](http://golang.org/pkg/database/sql/#DB)
2016-02-21 16:42:26 +03:00
```go
2016-02-21 18:09:24 +03:00
// Get generic database object *sql.DB to use its functions
2016-02-21 16:42:26 +03:00
db.DB()
2016-02-21 18:09:24 +03:00
// Connection Pool
2016-02-21 16:42:26 +03:00
db.DB().SetMaxIdleConns(10)
db.DB().SetMaxOpenConns(100)
2016-02-21 18:09:24 +03:00
// Ping
db.DB().Ping()
2016-02-21 16:42:26 +03:00
```