Home >Backend Development >Golang >About go using mysql testing

About go using mysql testing

藏色散人
藏色散人forward
2021-01-21 11:21:282342browse

The following tutorial column from golang will introduce you to go using mysql testing. I hope it will be helpful to friends who need it!

##Add the test code as follows

package main

import (
    "github.com/jmoiron/sqlx"
    _ "github.com/go-sql-driver/mysql"
    "fmt"
)

func main() {
    Db,err:=sqlx.Open("mysql","root:123456@tcp(127.0.0.1:3306)/ghnv2_test")
    if err != nil{
        fmt.Println("connect to mysql failed,",err)
        return
    }
    defer Db.Close()
    fmt.Println("connect to mysql success")

    //执行sql语句,切记这里的占位符是?
    result,err := Db.Exec("INSERT INTO sysuser_tag(tag_name,shop_id,user_id)VALUES (?,?,?)","运动",12,24)
    if err != nil{
        fmt.Println("insert failed,",err)
    }
    // 通过LastInsertId可以获取插入数据的id
    tagId,err:= result.LastInsertId()
    // 通过RowsAffected可以获取受影响的行数
    rowCount,err:=result.RowsAffected()
    fmt.Println("tag_id:",tagId)
    fmt.Println("rowCount:",rowCount)
}

Need to install the MySQL package


About go using mysql testingExecute

About go using mysql testing

Query select is as follows

package main

import (
    "github.com/jmoiron/sqlx"
    _ "github.com/go-sql-driver/mysql"
    "fmt"
)

func main() {
   
    Db,err:=sqlx.Open("mysql","root:123456@tcp(127.0.0.1:3306)/ghnv2_test")
    if err != nil{
        fmt.Println("connect to mysql failed,",err)
        return
    }
    defer Db.Close()
    fmt.Println("connect to mysql success")

    //执行查询操作
    rows,err := Db.Query("SELECT tag_name FROM sysuser_tag WHERE tag_id>=7")
    if err != nil{
        fmt.Println("select db failed,err:",err)
        return
    }
    // 这里获取的rows是从数据库查的满足tag_id>=5的所有行的tag_name信息,rows.Next(),用于循环获取所有
    for rows.Next(){
        var s string
        err = rows.Scan(&s)
        if err != nil{
            fmt.Println(err)
            return
        }
        fmt.Println(s)
    }
    rows.Close()

}
The result is as follows

About go using mysql testing The test database is as follows

More golang related technical articles , please visit the About go using mysql testinggo language column!

The above is the detailed content of About go using mysql testing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete