[Using go to develop blockchain] Obtaining data on the chain (02)

In the previous article, we completed the construction of the basic environment and read the configuration file through viper. In this chapter, we will complete the use of gorm to connect to the database and insert a piece of data

1. Configure database connection

1.1, create a new db.go

For the operation of the database, we use the gorm class library, and enter the following command in the terminal to install gorm:

go get gorm.io/gorm
go get gorm.io/driver/mysql   #使用mysql驱动

Create a new db.go in the config directory, the code is as follows:

package config

import (
	"fmt"
	"go-chain-data/config/setting"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func NewDBEngine(dbConfig *setting.DbConfig) (*gorm.DB, error) {
    
    
	conn := "%s:%s@tcp(%s)/%s?charset=%s&parseTime=%t&loc=Local"
	dsn := fmt.Sprintf(conn, dbConfig.Username, dbConfig.Pwd, dbConfig.Host, dbConfig.DbName, dbConfig.Charset, dbConfig.ParseTime)
	db, err := gorm.Open(mysql.Open(dsn))
	if err != nil {
    
    
		return nil, err
	}
	return db, nil
}

The NewDBEngine() method creates a gorm.DB object

The point to note here is that the gorm.io/driver/mysql package needs to be imported manually

1.2. Modify global.go

Add DBEngine definition:

DBEngine         *gorm.DB

1.3. Modify config.go

Add the SetupDBEngine() method to instantiate DBEngine, the code is as follows:

func SetupDBEngine() {
    
    
    var err error
    global.DBEngine, err = NewDBEngine(global.DbConfig)
    if err != nil {
    
    
            log.Panic("NewDBEngine error : ", err)
    }
}

1.4, modified main.go

In the init() method, add a call to the SetupDBEngine() method:

func init() {
    
    
    config.SetupConfig()
    config.SetupDBEngine()
}

2. Write entity classes

2.1. New block.go

First, create a models directory in the internal directory, and then create a new block.go in the models directory, the code is as follows:

package models

import (
	"go-chain-data/global"
	"gorm.io/gorm"
)

type Blocks struct {
    
    
	Id                int64  `json:"id" gorm:"primary_key;AUTO_INCREMENT"`
	BlockHeight       uint64 `json:"block_height" gorm:"column:block_height; default:0; comment:区块高度;"`
	BlockHash         string `json:"block_hash" gorm:"column:block_hash;default:''; comment:区块hash;"`
	ParentHash        string `json:"parent_hash" gorm:"column:parent_hash;default:''; comment:父hash;"`
	LatestBlockHeight uint64 `json:"latest_block_height" gorm:"column:latest_block_height;default: 0; comment:最后区块高度;"`
	*gorm.Model
}

func (b *Blocks) TableName() string {
    
    
	return "blocks"
}

func (b *Blocks) Insert() error {
    
    
	if err := global.DBEngine.Create(&b).Error; err != nil {
    
    
		return err
	}
	return nil
}

Among them, the TableName() method will be used later when we create a database table through gorm mapping (that is, the return parameter will be used as the name of the table) The Insert() method allows us to insert a
new record

3. Create tables using AutoMigrate

3.1. Modify db.go

Gorm provides a method AutoMigrate(), which can automatically create/update the table structure according to the model. We open db.go and add the following code at the end:

// MigrateDb 初始化数据库表
func MigrateDb() error {
    
    
    if err := global.DBEngine.AutoMigrate(&models.Blocks{
    
    }); err != nil {
    
    
            return err
    }
    return nil
}

Among them, models.Blocks means that we need gorm to help us create/update model objects. If there are more than one, we can add them in turn.

3.2, modified main.go

At the end of the init() method, add the following code:

	err := config.MigrateDb()
	if err != nil {
    
    
		log.Panic("config.MigrateDb error : ", err)
	}

Then, we execute the main() method in main.go, open the database connection tool, and find that gorm has automatically created the blocks table for us:
insert image description here

4. Test database connection

4.1 Test insertion

Open main.go and add the following code in the main() method:

	block := models.Blocks{
    
    
		BlockHeight:       1,
		BlockHash:         "hash",
		ParentHash:        "parentHash",
		LatestBlockHeight: 2,
	}
	err := block.Insert()
	if err != nil {
    
    
		log.Panic("block.Insert error : ", err)
	}

Then run the main() method, and the console outputs the following information:
insert image description here
We query the database and find that the data has been inserted:
insert image description here

This concludes the content of this chapter. In this chapter, we have completed the creation of the database connection and successfully inserted a record. In the next course, we will start to develop the function of obtaining data on the chain. Keep up the good work guys!

Please pay attention to the official account: Web3_preacher (web3_preacher) , reply "go to get the data on the chain" to receive the complete code

Guess you like

Origin blog.csdn.net/rao356/article/details/132210351