Golang Gorm 连接数据库

连接数据库


为了连接数据库,你首先要导入数据库驱动程序。例如:

Go 复制代码
import _ "github.com/go-sql-driver/mysql"

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

GORM 已经包含了一些驱动程序,为了方便的去记住它们的导入路径,你可以像下面这样导入
mysql 驱动程序

Go 复制代码
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"

支持的数据库


MySQL

注意: 为了正确的处理 time.Time ,你需要包含 parseTime 作为参数。 (More supported parameters)

Go 复制代码
import (
  "github.com/jinzhu/gorm"
  _ "github.com/jinzhu/gorm/dialects/mysql"
)

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

PostgreSQL

Go 复制代码
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

Go 复制代码
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,它可以通过 Docker 运行在你的 Mac, Linux 上。

Go 复制代码
import (
 "github.com/jinzhu/gorm"
 _ "github.com/jinzhu/gorm/dialects/mssql"
)
func main() {
  db, err := gorm.Open("mssql", "sqlserver://username:password@localhost:1433?da
tabase=dbname")
  defer db.Close()
}

不支持的数据库


GORM 官方支持以上四种数据库, 你可以为不支持的数据库编写支持,参考 GORM Dialects

相关推荐
怪我冷i6 小时前
使用vscode调试wails项目(golang桌面GUI)
vscode·golang
小吴同学(wlx)10 小时前
Golang 进阶3—— 协程&管道
golang
技术卷10 小时前
GO网络编程(三):海量用户通信系统1:登录功能初步
golang·网络编程
虽千万人 吾往矣13 小时前
golang gorm
开发语言·数据库·后端·tcp/ip·golang
__AtYou__1 天前
Golang | Leetcode Golang题解之第448题找到所有数组中消失的数字
leetcode·golang·题解
千年死缓1 天前
go+redis基于tcp实现聊天室
redis·tcp/ip·golang
吃着火锅x唱着歌1 天前
Redis设计与实现 学习笔记 第五章 跳跃表
golang
技术卷2 天前
Redis数据库与GO完结篇:redis操作总结与GO使用redis
数据库·redis·golang
white.tie2 天前
vscode配置golang
ide·vscode·golang
陈序缘2 天前
Go语言实现长连接并发框架 - 任务管理器
linux·服务器·开发语言·后端·golang