搭建好gin框架后,输入命令安装gorm所需要的依赖

go get -u github.com/jinzhu/gorm

导入两个gorm所用到的依赖

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

注意dialects的依赖中前面有一个 “_”

其他数据库只需要更改一下数据库的名字

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

用常量存数据库配置信息(在企业级项目中应该去找配置信息,如ymal文件中,这里使用常量替代)

const (
	host     = ""
	port     = 
	user     = ""
	password = ""
	dbname   = ""
)

连接数据库

	connStr := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
		host, port, user, password, dbname)

	var err error
	DB, err = gorm.Open("postgres", connStr)

	if err != nil {
		panic(err)
	}

	fmt.Println("Successfully connected to the PostgreSQL database!")

以下是全部代码以及一个案例,在项目中自行把握文件结构,这里来案例代码都放在main所在的文中了

package dao

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

const (
	host     = ""
	port     = 
	user     = ""
	password = ""
	dbname   = ""
)

var DB *gorm.DB

func InitSql() {

	connStr := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
		host, port, user, password, dbname)

	var err error
	DB, err = gorm.Open("postgres", connStr)

	if err != nil {
		panic(err)
	}

	fmt.Println("Successfully connected to the PostgreSQL database!")
}

最后记得在程序结束前关闭数据库资源哦

	defer dao.DB.Close()

 

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐