PostgreSQL数据库timestamp,date类型字段,GO读取格式化

本文介绍如何使用Go语言处理从PostgreSQL数据库中获取的timestamp和date类型数据,通过自定义LocalTime与LocalDate结构体及实现MarshalJSON方法来格式化输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

go语言从PostgreSQL数据库读取数据,
timestamp类型的字段,直接读取后为2018-01-01T15:59:24Z 格式
date类型字段,直接读取为2018-01-01T00:00:00Z 格式

需要做一下处理
定义LocalTime、LocalDate结构体
实现MarshalJSON接口,格式化一下数据

type LocalTime time.Time

// MarshalJSON satify the json marshal interface
func (l LocalTime) MarshalJSON() ([]byte, error) {
    stamp := fmt.Sprintf("\"%s\"", time.Time(l).Format("2006-01-02 15:04:05"))
    return []byte(stamp), nil
}

type LocalDate time.Time

// MarshalJSON satify the json marshal interface
func (l LocalDate) MarshalJSON() ([]byte, error) {
    stamp := fmt.Sprintf("\"%s\"", time.Time(l).Format("2006-01-02"))
    return []byte(stamp), nil
}

在定义接收数据的结构体时,定义成员类型为LocalTime、LocalDate,可以根据需要格式化出数据

type LogInfo struct {
    ID         int       `form:"id" json:"id" gorm:"id"`
    LogName    string    `form:"log_name" json:"log_name" gorm:"column:log_name"`
    CreateTime LocalTime `form:"create_time" json:"create_time" gorm:"column:create_time"`
    CreateDate LocalDate `form:"create_date" json:"create_date" gorm:"column:create_date"`
}
可以使用Go语言的database/sql包来获取MySQL表结构,然后根据不同的类型适配到postgresql数据库字段类型。 以下是一个示例代码,可以实现这个功能: ```go package main import ( "database/sql" "fmt" "log" _ "github.com/go-sql-driver/mysql" _ "github.com/lib/pq" ) func main() { // MySQL数据库连接配置 mysqlDb, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/database") if err != nil { log.Fatal(err) } defer mysqlDb.Close() // 查询MySQL表结构 rows, err := mysqlDb.Query("SHOW COLUMNS FROM table_name") if err != nil { log.Fatal(err) } defer rows.Close() // PostgreSQL数据库连接配置 pgDb, err := sql.Open("postgres", "postgres://user:password@localhost:5432/database?sslmode=disable") if err != nil { log.Fatal(err) } defer pgDb.Close() // 遍历MySQL表字段 for rows.Next() { var ( field string mysqlType string ) if err := rows.Scan(&field, &mysqlType); err != nil { log.Fatal(err) } // 适配MySQL字段类型PostgreSQL字段类型 var pgType string switch mysqlType { case "int": pgType = "integer" case "varchar", "text": pgType = "text" case "datetime": pgType = "timestamp" // 其他类型适配 default: log.Fatalf("unsupported type: %s", mysqlType) } // 创建PostgreSQL表结构 _, err := pgDb.Exec(fmt.Sprintf("ALTER TABLE table_name ADD COLUMN %s %s", field, pgType)) if err != nil { log.Fatal(err) } } } ``` 以上代码中,我们通过Go语言的database/sql包连接MySQL和PostgreSQL数据库,并查询MySQL表结构。 然后,我们根据不同的MySQL字段类型,适配到相应的PostgreSQL字段类型,并创建PostgreSQL表结构。 需要注意的是,以上代码只是一个示例,实际使用中需要根据具体业务需求进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值