centos

怎样在CentOS上使用Golang数据库

小樊
41
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
看了该问题的人还看了