golang learning ---- database operations

golang operational database

Process golang operation of the database is very simple, here's a simple CRUD operations, where we use the MySQL database as an example.

Connect to the database

Connect to the database we first need to download the appropriate database drivers, where we chose MySQL database-driven, so we went to pull the driver. Prior to this we need to have git- Download: https://git-scm.com/, if the download speed is slow, it is recommended to use the following address https://npm.taobao.org/mirrors/git-for-windows/ selection you can download the appropriate version.

  1. go get github.com/go-sql-driver/mysql Pulling the drive to find if the other database or modify the name back to the corresponding github

  2. import ( _ "github.com/go-sql-driver/mysql") Introducing the driver package in the code, do calls the init method mysql package.

  3. var db *sql.DB
    func conn(){
    open, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/demo_db") // 这里的地址若是本地3306接口可以写成user:password@tcp(127.0.0.1:3306)/demo_db
    if err!=nil {   log.Fatal(err)   panic(err)} 
    db = open
    }

Data Manipulation

Insert data

//  数据添加
func add(){  
    _, err := db.Exec("insert into user (name, age, email) value (?,?,?)", "张三", 20, "[email protected]")   
    if err!=nil {      
        fmt.Println(err)      
        panic(err)   
    }
}

delete data

//  数据删除
func remove(){   
    exec, err := db.Exec("delete from user where id = ?", 6)   
    if err != nil {      
        fmt.Println(err)      
        panic(err)   
    }   
    fmt.Println(exec.RowsAffected())
}

change the data

func modify(){
    exec, err := db.Exec("update user set name = ?,age = ? where id = ?", "babiqus", "22", 6)   
    if err!=nil {    
        fmt.Println(err)     
        panic(err)  
    }   
    fmt.Println(exec.RowsAffected())
}

Query data

func query() {   
    query, err := db.Query("select * from user")  
    if err!=nil {    
        log.Fatal(err)    
        panic(err)  
    }  
    defer query.Close()   
    // 必须要把 query 里的内容读完,或者显式调用 Close() 方法,   
    // 否则在 defer 的 rows.Close() 执行之前,连接永远不会释放   
    var userList []User
    for query.Next(){   
        user := new(User)   
        err := query.Scan(&user.id,&user.name,&user.age,&user.email)    
        if err != nil{    
            log.Fatal(err)    
        }    
        userList = append(userList, *user)   
    }  
    for _, value := range userList {  
        fmt.Println(value)  
    }
}

use

func init(){  
    conn()
}
func main() {   
    //add()  
    //modify()
    //remove()  
    query()
    defer db.Close()
}

Guess you like

Origin www.cnblogs.com/bananafish/p/12079521.html