Connecting to database

Connecting to database

In order to connect to a database, you need to first import the database’s driver. For example:

import _ "github.com/go-sql-driver/mysql"

GORM has wrapped some drivers, to make easier to remember their import path, so you could import the mysql driver with

import _ "github.com/jinzhu/gorm/dialects/mysql"
// import _ "github.com/jinzhu/gorm/dialects/postgres"
// import _ "github.com/jinzhu/gorm/dialects/sqlite"
// import _ "github.com/jinzhu/gorm/dialects/mssql"

Supported Databases

MySQL

NOTE: In order to handle time.Time correctly, you need to include parseTime as a parameter. (More supported parameters)

import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)

func main() {
db, err := gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local")
defer db.Close()
}

PostgreSQL

import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)

func main() {
db, err := gorm.Open("postgres", "host=myhost port=myport user=gorm dbname=gorm password=mypassword")
defer db.Close()
}

Sqlite3

import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)

func main() {
db, err := gorm.Open("sqlite3", "/tmp/gorm.db")
defer db.Close()
}

SQL Server

Get started with SQL Server, it can running on your Mac, Linux with Docker

import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mssql"
)

func main() {
db, err := gorm.Open("mssql", "sqlserver://username:password@localhost:1433?database=dbname")
defer db.Close()
}

Unsupported Databases

GORM officially supports above four databases, you could write dialects for unsupported databases, refer GORM Dialects