Implementation code for operating mysql database in golang

Implementation code for operating mysql database in golang

Preface

Golang provides the database/sql package for accessing SQL databases. As the entry object for operating the database, sql.DB mainly provides us with two important functions:

•sql.DB provides us with the ability to manage the opening and closing of underlying database connections through the database driver.

•sql.DB manages the database connection pool for us

It should be noted that sql.DB represents an abstract access interface for operating the database, rather than a database connection object; it can open and close database connections and manage connection pools based on the driver. The connection in use is marked as busy and returns to the connection pool after use to wait for the next use. Therefore, if you do not release the connection back to the connection pool, it will cause too many connections to exhaust system resources.

Introduction to MySQL operation with Golang

The feeling of operating MySQL database in Golang is a bit like the operation of MySQL in PDO in PHP. If you are originally a PHPer, you will find it very familiar to switch to Golang. The overall feeling is very simple

Notes on Golang's operation of MySQL

Golang implements the standard library for MySQL operations but does not implement the MySQL driver

Therefore, we need to download the go-sql-driver driver package from github first (it is recommended to execute in the src directory). The command is as follows:

go get github.com/go-sql-driver/mysql

Create a table field in the test database as follows

CREATE TABLE IF NOT EXISTS `test`.`user` (
 `user_id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'User ID',
 `user_name` VARCHAR(45) NOT NULL COMMENT 'User name',
 `user_age` TINYINT(3) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'User age',
 `user_sex` TINYINT(3) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'User gender',
 PRIMARY KEY (`user_id`))
 ENGINE = InnoDB
 AUTO_INCREMENT = 1
 DEFAULT CHARACTER SET = utf8
 COLLATE = utf8_general_ci
 COMMENT = 'User table'

Implementing the insert operation on data

package main
import (
 "fmt"
 "database/sql"
 //Import mysql driver_ "github.com/go-sql-driver/mysql" 
)
func main(){
 //Use Open in the database/sql package to connect to the database db, err := sql.Open("mysql","root:root@tcp(localhost:3306)/test?charset=utf8")
 if err != nil {
 fmt.Println("Failed to connect to database:",err)
 return 
 }
 //Use the DB structure instance method Prepare to preprocess the insert. Prepare will return a stmt object stmt, err := db.Prepare("insert into `user`(user_name,user_age,user_sex)values(?,?,?)")
 if err!=nil{
 fmt.Println("Preprocessing failed:",err)
 return  
 }
 //Use the Stmt object to execute the preprocessing parameters result,err := stmt.Exec("pengjin",33,"男")
 if err!=nil{
 fmt.Println("Failed to execute preprocessing:",err)
 return  
 }else{
 rows,_ := result.RowsAffected()
 fmt.Println("Execution successful, number of affected rows", rows,"rows")
 }
}

The above code gives a feeling of operating pdo in PHP. In fact, the above code can also be implemented directly through the Exec method of the Stmt instance without writing the Prepare method.

Summarize

The above is the implementation code for operating MySQL database in golang introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank everyone for their support of the 123WORDPRESS.COM website!

You may also be interested in:
  • Golang connects to mysql through ssh proxy
  • Connecting to MySQL database in golang
  • Complete steps of Golang to operate MySql database
  • How to operate MySQL in Golang
  • How to implement mysql database backup in golang
  • Golang operation connects to the database to implement mysql transaction example

<<:  Using JS timer to move elements

>>:  A record of a Linux server intrusion emergency response (summary)

Recommend

How to regularly clean up docker private server images

Using CI to build docker images for release has g...

Manually install mysql5.7.10 on Ubuntu

This tutorial shares the process of manually inst...

How to implement gzip compression in nginx to improve website speed

Table of contents Why use gzip compression? nginx...

CSS3 realizes particle animation effect when matching kings

When coding, you will find that many things have ...

Summary of Binlog usage of MySQL database (must read)

I won't go into details about how important b...

Detailed explanation of Angular data binding and its implementation

Table of contents Preface What is data binding? T...

Pure CSS to achieve hover image pop-out pop-up effect example code

Implementation principle The main graphics are co...

How to clean up Alibaba Cloud MySQL space

Today I received a disk warning notification from...

Dockerfile implementation code when starting two processes in a docker container

I want to make a docker for cron scheduled tasks ...

How to install SVN server under Linux

1. Yum installation yum install subversion 2. Con...

Detailed explanation of error handling examples in MySQL stored procedures

This article uses an example to describe the erro...

Using js to implement the two-way binding function of data in Vue2.0

Object.defineProperty Understanding grammar: Obje...

Util module in node.js tutorial example detailed explanation

Table of contents Starting from type judgment Str...