We know that the Bitcoin client’s block information is stored in the LevelDB database. Since we want to develop the public chain based on GO, the database used here is boltDB based on GO.

The installation

Using the go get

$ go get github.com/boltdb/boltd / ...
Copy the code

After the installation is successful, we will see in the go directory:

The basic use

Create and open the database

Note: gland runs directly here, and the my.db generated is in the upper directory of main.go. Command line build is the current directory when running!!

// Gland runs directly here, and my.db is generated in the upper directory of main.go; Command line build is the current directory when running!! db, err := bolt.Open("chaorsBlock.db", 0600, nil)
	iferr ! = nil { log.Fatal(err) } defer db.Close()Copy the code

After you open it, you can handle it in two ways: read-write and read-only. The read-write method starts with the db.Update method, which is commonly used to create tables and insert new data into tables. Read-only operations start with the db.view method and are often used to query table data.

Create a new table
Update(func(tx * bolt.tx) error {// Check whether the table to be created exists b := tx.bucket ([]byte("MyBlocks"))
		ifB == nil {// create call"MyBucket"Err := tx.createBucket ([]byte("MyBlocks"))
			iferr ! Log.Fatal(err)}} // Must return nilreturnNil}) // Database update failediferr ! = nil { log.Fatal(err) }Copy the code
Update table contents
Update(func(tx * bolt.tx) error {err = db.update (func(tx * bolt.tx) error"MyBucket"Table B := tx.bucket ([]byte("MyBlocks") // Add data to the tableifb ! Err := b.put ([]byte("l"), []byte("0x0000"))
			err := b.Put([]byte("ll"), []byte("0x0001"))
                        err := b.Put([]byte("lll"), []byte("0x0002"))
			iferr ! = nil {log.fatal (err)}} // Must return nilreturnNil}) // Database update failediferr ! = nil { log.Fatal(err) }Copy the code
Table query
Func (tx * bolt.tx) error {err = db.View(func(tx * bolt.tx) error"MyBucket"Table B := tx.bucket ([]byte("MyBlocks") // Add data to the tableifb ! = nil { data := b.Get([]byte("l"))
			fmt.Printf("%s\n", data)
			data := b.Get([]byte("l"))
			fmt.Printf("%s\n", data)} // Always return nilreturnNil}) // database query failediferr ! = nil { log.Fatal(err) }Copy the code

Basic use of BolTDB to learn this first, build a public chain with database storage blocks probably only so much, later specific boltDB related to other knowledge targeted learning.

The source code is here, if you like, please remember to give a little star, or fork. Welcome to discuss blockchain knowledge together, and make progress together!

For more original articles on blockchain technology, please visitchaors

.

### The Internet upends the world, blockchain upends the Internet!

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — 20180623 19:06