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

Detailed application of Vue dynamic form

Overview There are many form requirements in the ...

Implementation of CSS equal division of parent container (perfect thirds)

The width of the parent container is fixed. In or...

Centos7.5 installs mysql5.7.24 binary package deployment

1. Environmental preparation: Operating system: C...

Example of using UserMap in IMG

usemap is an attribute of the <img> tag, use...

Why Use DOCTYPE HTML

You know that without it, the browser will use qui...

10 Best Practices for Building and Maintaining Large-Scale Vue.js Projects

Table of contents 1. Use slots to make components...

Use docker to deploy tomcat and connect to skywalking

Table of contents 1. Overview 2. Use docker to de...

How to process blob data in MySQL

The specific code is as follows: package epoint.m...

Details of various font formats in HTML web pages

This section starts with the details of text modi...

Implementation of breakpoint resume in Node.js

Preface Normal business needs: upload pictures, E...

A brief discussion on the principle of js QR code scanning login

Table of contents The essence of QR code login Un...

Web Standard Application: Redesign of Tencent QQ Home Page

Tencent QQ’s homepage has been redesigned, and Web...

Analysis of the Principle and Method of Implementing Linux Disk Partition

remember: IDE disk: the first disk is hda, the se...