溫馨提示×

怎樣在CentOS上使用Golang數據庫

小樊
49
2025-02-24 18:27:46
欄目: 編程語言

在CentOS上使用Golang與數據庫進行交互是一個常見的任務,尤其是在構建Web應用程序時。以下是一些步驟和庫,可以幫助你在CentOS上使用Golang連接和操作數據庫。

安裝Golang

首先,確保你的CentOS系統上已經安裝了Golang。你可以按照以下步驟進行安裝:

  1. 下載最新版本的Golang二進制文件:
wget https://golang.org/dl/go1.17.2.linux-amd64.tar.gz
  1. 解壓下載的二進制文件到 /usr/local 目錄下:
sudo tar -C /usr/local -xzf go1.17.2.linux-amd64.tar.gz
  1. 設置Golang的環境變量。編輯 /etc/profile 文件,并添加以下內容:
export PATH=$PATH:/usr/local/go/bin
  1. 使環境變量生效:
source /etc/profile

現在,你可以使用 go version 命令驗證安裝是否成功。

安裝數據庫

在CentOS上,你可以安裝多種數據庫,如MySQL、PostgreSQL等。以下是安裝MySQL的示例步驟:

安裝MySQL

  1. 安裝MySQL的依賴項:
sudo yum install -y mysql-devel
  1. 下載并安裝MySQL:
wget https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm
sudo yum localinstall mysql80-community-release-el7-3.noarch.rpm
  1. 啟動MySQL服務并設置開機自啟動:
sudo systemctl start mysqld
sudo systemctl enable mysqld
  1. 運行安全安裝腳本以配置MySQL:
sudo mysql_secure_installation

按照提示設置root密碼和其他安全選項。

使用Golang連接MySQL

在CentOS上使用Golang連接MySQL數據庫,你可以使用一些流行的庫,如 gormgo-sql-driver/mysql。以下是使用 gorm 連接MySQL的示例:

  1. 安裝 gormmysql 驅動:
go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql
  1. 編寫Golang代碼連接MySQL:
package main

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

type User struct {
    ID   uint
    Name string
    Age  int
}

func main() {
    dsn := "user:password@tcp(localhost:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
    if err != nil {
        panic("failed to connect database")
    }

    // Migrate the schema
    db.AutoMigrate(&User{})

    // Create
    db.Create(&User{Name: "John", Age: 30})

    // Read
    var user User
    db.First(&user, 1) // find user with id 1
    db.First(&user, "name = ?", "John") // find user with name "John"

    // Update - update user's age
    db.Model(&user).Update("Age", 25)

    // Delete - delete user
    db.Delete(&user, 1)
}

安裝PostgreSQL

以下是安裝PostgreSQL的示例步驟:

  1. 安裝PostgreSQL的yum倉庫:
sudo yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm
  1. 使用yum命令安裝PostgreSQL服務器:
sudo yum install -y postgresql15-server postgresql15-contrib
  1. 初始化數據庫并啟動PostgreSQL服務:
/usr/pgsql-15/bin/postgresql-15-setup initdb
sudo systemctl start postgresql-15
sudo systemctl enable postgresql-15
  1. 允許遠程連接并配置訪問權限:
sudo vi /var/lib/pgsql/15/data/postgresql.conf
# 修改 listen_addresses 為 '*'
sudo vi /var/lib/pgsql/15/data/pg_hba.conf
# 添加允許遠程連接的配置
  1. 重啟服務并設置PostgreSQL用戶和密碼:
sudo systemctl restart postgresql-15
sudo -i -u postgres psql
# 設置密碼
ALTER USER postgres PASSWORD 'your_password';
\q

使用Golang連接PostgreSQL

以下是使用 database/sql 包連接PostgreSQL的示例:

  1. 安裝 database/sqllib/pq
go get -u github.com/lib/pq
  1. 編寫Golang代碼連接PostgreSQL:
package main

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

type User struct {
    ID   int
    Name string
    Age  int
}

func main() {
    psqlInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
        "localhost", 5432, "postgres", "your_password", "mydb")
    db, err := sql.Open("postgres", psqlInfo)
    if err != nil {
        panic(err)
    }
    defer db.Close()

    // Ping database to see if it's still alive
    err = db.Ping()
    if err != nil {
        panic(err)
    }

    fmt.Println("Successfully connected!")
}

通過以上步驟,你可以在CentOS上成功安裝和使用Golang與數據庫進行交互。根據你的具體需求,選擇合適的數據庫和相應的Golang庫進行開發。

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