溫馨提示×

如何在Ubuntu上使用Golang連接數據庫

小樊
46
2025-08-15 18:28:08
欄目: 編程語言

在Ubuntu上使用Golang連接數據庫,你需要遵循以下步驟:

  1. 安裝Go語言環境:首先,確保你已經在Ubuntu系統上安裝了Go語言環境。如果還沒有安裝,可以通過以下命令安裝:
sudo apt update
sudo apt install golang-go
  1. 安裝數據庫驅動:根據你要連接的數據庫類型,安裝相應的Go語言驅動。以下是一些常見數據庫的驅動安裝方法:
  • MySQL:
go get -u github.com/go-sql-driver/mysql
  • PostgreSQL:
go get -u github.com/lib/pq
  • MongoDB:
go get -u go.mongodb.org/mongo-driver/mongo
  • SQLite:
go get -u github.com/mattn/go-sqlite3
  1. 編寫Go代碼:創建一個Go文件(例如:main.go),并編寫連接數據庫的代碼。以下是一些示例:
  • MySQL:
package main

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
)

func main() {
	dsn := "username:password@tcp(localhost:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		panic(err)
	}
	defer db.Close()

	err = db.Ping()
	if err != nil {
		panic(err)
	}

	fmt.Println("Connected to the database!")
}
  • PostgreSQL:
package main

import (
	"database/sql"
	"fmt"
	_ "github.com/lib/pq"
)

func main() {
	connStr := "user=username dbname=dbname password=password sslmode=disable"
	db, err := sql.Open("postgres", connStr)
	if err != nil {
		panic(err)
	}
	defer db.Close()

	err = db.Ping()
	if err != nil {
		panic(err)
	}

	fmt.Println("Connected to the database!")
}
  • MongoDB:
package main

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
)

func main() {
	clientOptions := options.Client().ApplyURI("mongodb://username:password@localhost:27017")
	client, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Disconnect(context.TODO())

	err = client.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Connected to the database!")
}
  • SQLite:
package main

import (
	"database/sql"
	"fmt"
	_ "github.com/mattn/go-sqlite3"
)

func main() {
	db, err := sql.Open("sqlite3", "./test.db")
	if err != nil {
		panic(err)
	}
	defer db.Close()

	err = db.Ping()
	if err != nil {
		panic(err)
	}

	fmt.Println("Connected to the database!")
}
  1. 運行Go程序:在終端中,導航到包含Go文件的目錄,然后運行以下命令:
go run main.go

如果一切正常,你應該看到 “Connected to the database!” 的輸出。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女