Golang Gorm がデータベースに接続します

データベースに接続する


データベースに接続するには、まずデータベース ドライバーをインポートする必要があります。例:

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

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)
GORM にはすでにいくつかのドライバが含まれています。インポート パスを覚えておくと便利なように、次のようにインポートできます。 a>
mysql 驱动程序
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 をパラメータ。 (サポートされるパラメータの追加)

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
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()
}
スクライト3
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サーバー


SQL Server を使ってみましょう Docker 経由で で実行できます。 MacLinux

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 は上記の 4 つのデータベースを正式にサポートしています。サポートされていないデータベースのサポートを作成できます。GORM の方言 を参照してください。

おすすめ

転載: blog.csdn.net/qq_34556414/article/details/134327065