1024programmer Java Go add, delete, modify and check – mysql

Go add, delete, modify and check – mysql

Scan function explanation
How do we read data entered by the user from the keyboard (console)? Input refers to reading data from the keyboard or other standard input (os.Stdin). The simplest method is to use the Scan- or Sscan-series functions in the fmt package

The scan function will identify the content around spaces, even if the newline symbol exists, it will not affect the acquisition of the content by scan
The scanln function will recognize the content around spaces, but will end immediately once it encounters a newline character, regardless of whether there is any subsequent content that requires input.

Operation database

1. Guide the package and connect

import (
 "database/sql"
 "fmt"
 _ "github.com/Go-SQL-Driver/MySQL"
 

)

db,err := sql.Open("mysql","root:123456@tcp(127.0.0.1:3306)/test?charset=utf8")
 if err != nil{
 fmt.Printf("connect mysql fail ! [%s]",err)
 }else{
 fmt.Println("connect to mysql success")
 }
 

2. Add

result,err := db.Exec("INSERT INTO person(height,address,head)VALUES (?,?,?)","8","8","8")
 if err != nil{
 fmt.Println("insert failed,",err)
 }
 userId,err:= result.LastInsertId()
 rowCount,err:=result.RowsAffected() //Affected rows
 fmt.Println("user_id:",userId)
 fmt.Println("rowCount:",rowCount)
 

3. Query
// The Scan method will read data from the input end and store the processing result in the receiving end. The receiving end must be a valid pointer.
// Scanln is similar to Scan. When scan encounters a newline, it treats it as a space. When scanln encounters a newline, it stops scanning.

rowsQuery,err := db.Query("SELECT * FROM person WHERE )
 if err != nil{
 fmt.Println("select db failed,err:",err)
 return
 }
 for rowsQuery.Next() {
 var height int
 var head string
 var address string
 err = rowsQuery.Scan(&head,&height,&address)// The Scan method will read data from the input end and store the processing result in the receiving end. The receiving end must be a valid pointer.
 if err != nil {
 fmt.Println(err)
 return
 }
 fmt.Println(height,address,head)
 }
 rowsQuery.Close()
 }
 

4Delete

rowsDelete,err:=db.Exec("DELETE FROM person WHERE )
 

5 changes

rowsUpdate,err:=db.Exec("UPDATE person SET address=0 WHERE )
 

Code Appendix

 package main

 import (
 "database/sql"
 "fmt"
 _ "github.com/Go-SQL-Driver/MySQL"
 )
 func main() {
 /* db,err :=sql.Open("mysql","root:123456@tcp(127.0.0.1:3306)/person?charset=utf8")*/
 db,err := sql.Open("mysql","root:123456@tcp(127.0.0.1:3306)/test?charset=utf8")
 if err != nil{
 fmt.Printf("connect mysql fail ! [%s]",err)
 }else{
 fmt.Println("connect to mysql success")
 }
 /*result,err := db.Exec("INSERT INTO person(height,address,head)VALUES (?,?,?)","8","8","8")
 if err != nil{
 fmt.Println("insert failed,",err)
 }
 userId,err:= result.LastInsertId()
 rowCount,err:=result.RowsAffected()
 fmt.Println("user_id:",userId)
 fmt.Println("rowCount:",rowCount)*/
 	
 	
 	
 /*rowsQuery,err := db.Query("SELECT * FROM person WHERE )
 if err != nil{
 fmt.Println("select db failed,err:",err)
 return
 }
 for rowsQuery.Next() {
 var height int
 var head string
 var address string
 err = rowsQuery.Scan(&head,&height,&address)
 if err != nil {
 fmt.Println(err)
 return
 }
 fmt.Println(height,address,head)
 }
 rowsQuery.Close()*/
 	
 /* rowsDelete,err:=db.Exec("DELETE FROM person WHERE )
 	
 fmt.Println(rowsDelete.LastInsertId())*/
 	
 rowsUpdate,err:=db.Exec("UPDATE person SET address=0 WHERE )
 fmt.Print(
 rowsUpdate.LastInsertId())
 }
 

Postman sends a POST request to add data to the database
mysql.go

 import (
 "database/sql"
 "log"
 _ "github.com/Go-SQL-Driver/MySQL"
 )

 typeUser struct {
 Id int `json:"id" form:"id"`
 Username string `json:"username" form:"username"`
 Password string `json:"password" form:"password"`
 }

 func DBConn()(db *sql.DB) {
 dbDriver := "mysql"
 dbUser := "root"
 dbPass := "123456"
 dbName := "test"
 db, err := sql.Open(dbDriver, dbUser+":"+dbPass+"@/"+dbName)
 if err != nil { panic(err.Error()) }
 return db }
 func add(user User) (Id int, err error) {

 //1.Operation database
 db:=DBConn()
 //Delay the closing of the database connection
 defer db.Close()
 stmt, err := db.Prepare("INSERT INTO person(id,username, password) VALUES (?,?, ?)")
 if err
 //convert id type
 Id = int(id)
 defer stmt.Close()
 return
 

main.go

router.POST("/add", func(c *gin.Context) {
 var uUser
 err := c.Bind(&u)
 if err != nil {
 log.Fatal(err)
 }
 Id, err := add(u)
 fmt.Print("id=", Id)
 c.JSON(http.StatusOK, gin.H{
 "message": fmt.Sprintf("%s inserted successfully", u.Username),
 })
 })
 

Insert image description here

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/724842

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索