Get the App
SLTechnology News&Howtos  ›  Database  › 

How to operate mysql database in golang

Shulou Source: shulou.com Published: 2022-05-31 22:08:31 09月22日 Update

This article introduces how to operate the mysql database in golang, the content is very detailed, interested friends can refer to, hope to be helpful to you.

Introduction to Golang Operation mysql

The feeling of Golang operating mysql database is a bit like the operation of pdo to mysql in php. Assuming that you are originally phper to golang, it is very friendly to accept, and the overall feeling is very simple.

Attention points of Golang operating mysql

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

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

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

Create table fields in the test database as follows

CREATE TABLE IF NOT EXISTS `test`.`user` (`user id` INT (11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'user number', `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'

Realize the insert operation to the data

Package mainimport ("fmt"database/sql" / / Import the driver of mysql _ "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 the database:" Err) return} / / insert with Prepare preprocessing using DB structure instance method, Prepare will return a stmt object stmt,err: = db.Prepare ("insert into `user` (user_name,user_age,user_sex) values (?,?)") If erratic preprocessing nil {fmt.Println ("preprocessing failed:", err) return} / / use Stmt object to perform preprocessing parameters result,err: = stmt.Exec ("pengjin", 33, "male") if erratic preprocessing nil {fmt.Println ("preprocessing failed:", err) return} else {rows,_: = result.RowsAffected () fmt.Println ("successful execution, number of rows affected", rows "OK")}} on how to operate the mysql database in golang, so much for sharing. I hope the above content can be of some help to you and learn more knowledge. If you think the article is good, you can share it for more people to see.

Tags: Data database user preprocessing driver content object feeling more help good success interest original parameter name command field instance boy Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info MariaDB Redmi Microsoft Xiaomi