SoFunction
Updated on 2025-03-05

Use Gorm to operate Oracle database pit records

Gorm is the most commonly used Go language orm library, but currently, Gorm does not support oracle drivers, and requires a third driver. Recently, a project wants to write data to oracle to record the pitfalls you have stepped on.

Download dependencies

go get /cengsin/oracle

This driver does not match the latest gorm library. You need to downgrade gorm to version 1.21, otherwise the error ".../cengsin/[email protected]/:53:59: unknown field 'WithReturning' in struct literal of type" will appear

Project structure

Contains and a model directory.

|——oracle_test
|    |——model
|        |——
|    |——
|    |——

Edit downgrades gorm

module oracle_test
 
go 1.16
 
require (
    /cengsin/oracle v1.0.0
    /gorm v1.21.16
)

Run the go mod tidy command to take effect

Define model type

Suppose there is a table shops with store information in the database, including two fields: ID and store name, and write the following file. The structure method TableName specifies the data table corresponding to the change type.

package model
 
type ShopInfo struct {
    ShopId   string `gorm:"column:SHOPID;not null"`
    ShopName string `gorm:"column:SHOPNAME;not null"`
}
 
func (s *ShopInfo) TableName() string {
    return "shops"
}

Connect to the database

In the connection name "database/[email protected]:1521/XE", database is the database name, password is the password, and XE is the service name. LogLevel prints most sql statements, and sets to only print sql statements that have run errors.

package main
 
import (
    "fmt"
    "log"
    "os"
    "time"
 
    "oracle_test/model"
 
    "/cengsin/oracle"
    "/gorm"
    "/gorm/logger"
)
 
func test() {
    ("initial database connect……")
    db, err := (("database/[email protected]:1521/XE"), &{
        Logger: ((, "\r\n", ), {
            SlowThreshold: 1 * ,
            LogLevel:      , //Print level            Colorful:      true,
        }),
        //SkipDefaultTransaction: true,
    })
 
    if err != nil {
        (err)
    }
 
    if e := (&{}); e != nil {
        (())
    }
    shopInfo := new()
    (shopInfo)
    (*shopInfo)
}

Test run

go run ./

This is the article about using Gorm to operate Oracle databases and logs into pits. For more related content on Gorm operation Oracle, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!