Golang运行git main.go时出现的终端错误怎么解决

Golang运行git main.go时出现的终端错误怎么解决 为什么启动项目时会遇到这个错误

用户迁移

package migrations

import (
	"fmt"

	"gorest/models"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

var DB *gorm.DB

var err error

const dbinfo = "host=localhost user=postgres password=*****  dbname=BigDb port=5432 sslmode=disable"

func InitalMigration() {
	DB, err = gorm.Open(postgres.Open(dbinfo), &gorm.Config{})

	if err != nil {
		fmt.Println(err.Error())
	}
	DB.AutoMigrate(&models.User{})
}

错误 *2022/12/27 13:56:05 C:/Users/baris/OneDrive/Masaüstü/GOREST/migrations/usermigration.go:19 [error] 初始化数据库失败,错误原因:无法连接到 host=localhost user=postgres database=BigDb:服务器错误 (FATAL: database “BigDb” does not exist (SQLSTATE 3D000)) 无法连接到 host=localhost user=postgres database=BigDb:服务器错误 (FATAL: database “BigDb” does not exist (SQLSTATE 3D000))

2022/12/27 13:56:05 C:/Users/baris/OneDrive/Masaüstü/GOREST/migrations/usermigration.go:24 无法连接到 host=localhost user=postgres database=BigDb:服务器错误 (FATAL: database “BigDb” does not exist (SQLSTATE 3D000)) [46.255ms] [rows:-] SELECT count(*) FROM information_schema.tables WHERE table_schema = CURRENT_SCHEMA() AND table_name = ‘users’ AND table_type = ‘BASE TABLE’

2022/12/27 13:56:05 C:/Users/baris/OneDrive/Masaüstü/GOREST/migrations/usermigration.go:24 无法连接到 host=localhost user=postgres database=BigDb:服务器错误 (FATAL: database “BigDb” does not exist (SQLSTATE 3D000)) [45.179ms] [rows:0] CREATE TABLE “users” (“id” bigserial,“created_at” timestamptz,“updated_at” timestamptz,“deleted_at” timestamptz,“first_name” text,“last_name” text,“email” text,“password” text,PRIMARY KEY (“id”))*


更多关于Golang运行git main.go时出现的终端错误怎么解决的实战教程也可以访问 https://www.itying.com/category-94-b0.html

4 回复

创建数据库。

更多关于Golang运行git main.go时出现的终端错误怎么解决的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


我该如何解决这个错误

原因在于你复制到这里却没有阅读的错误信息中。

你的 PostgreSQL 实例中没有名为 BigDb 的数据库。

错误信息显示数据库 “BigDb” 不存在。你需要先在 PostgreSQL 中创建这个数据库,或者修改连接字符串使用已存在的数据库。

以下是解决方案:

1. 创建数据库(推荐)

# 连接到 PostgreSQL
psql -U postgres

# 创建数据库
CREATE DATABASE BigDb;
\q

2. 修改连接字符串使用已存在的数据库

// 修改 dbinfo 常量中的 dbname 参数
const dbinfo = "host=localhost user=postgres password=***** dbname=你的现有数据库名 port=5432 sslmode=disable"

3. 完整的迁移代码示例:

package migrations

import (
	"fmt"
	"log"

	"gorest/models"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

var DB *gorm.DB

func InitalMigration() {
	dsn := "host=localhost user=postgres password=***** dbname=BigDb port=5432 sslmode=disable"
	
	var err error
	DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatalf("数据库连接失败: %v", err)
	}

	// 自动迁移
	err = DB.AutoMigrate(&models.User{})
	if err != nil {
		log.Fatalf("自动迁移失败: %v", err)
	}
	
	fmt.Println("数据库迁移成功")
}

4. 检查 PostgreSQL 服务是否运行:

# Windows
net start postgresql

# Linux/macOS
sudo systemctl status postgresql

5. 验证数据库是否存在:

psql -U postgres -l

错误代码 SQLSTATE 3D000 明确表示数据库不存在。按照上述步骤创建数据库后,你的程序应该能正常运行。

回到顶部