Go basic programming practice (10) – Database

Time:2020-1-15

Read data from database

Download SQLite3 visualizer at http://sqlitebrowser.org/ and create it in the same directory as main.gopersonal.dbDatabase, create the table as follows:
Go basic programming practice (10) - Database

package main

import (
    "database/sql"
    "fmt"

    _ "github.com/mattn/go-sqlite3"
)
//Using struct type to map data from SQL database to objects in memory
type Profile struct {
    ProfileId int
    FirstName string
    LastName string
    Age int
}

func main() {
    db, err := sql.Open("sqlite3", "./personal.db")
    checkError(err)
    var profile Profile
    //Query can use parameters
    rows, err := db.Query("select ProfileId, FirstName, LastName, Age from Profile where FirstName = ? and LastName = ?", "Tarik", "Guney")
    checkError(err)
    for rows.Next() {
        err := rows.Scan(&profile.ProfileId, &profile.FirstName, &profile.LastName, &profile.Age)
        checkError(err)
        fmt.Println(profile)
    }
    rows.Close()
    db.Close()
}

func checkError(err error) {
    if err != nil {
        panic(err)
    }
}

Insert data into database

package main

import (
    _ "github.com/mattn/go-sqlite3"
    "database/sql"
    "fmt"
)

type Profile struct{
    ProfileId int
    FirstName string
    LastName string
    Age int
}

func main(){
    db, err := sql.Open("sqlite3", "./personal.db")
    checkError(err)
    /*Update database data
    statement, err := db.Prepare("update Profile set FirstName = ? where ProfileId = ?")
    checkError(err)
    statement.Exec("Martha", 5)
    */
    statement, err := db.Prepare("insert into Profile (FirstName, LastName, Age) values(?,?,?)")
    checkError(err)
    statement.Exec("Jessica", "McArthur", 30)
    /*Delete database data
    statement ,err := db.Prepare("delete from Profile where  ProfileId = ?")
    checkError(err)
    statement.Exec(3)
    */
    var profile Profile
    rows, err := db.Query("select ProfileId, FirstName, LastName, Age from Profile")
    checkError(err)
    for rows.Next(){
        err := rows.Scan(&profile.ProfileId, &profile.FirstName, &profile.LastName, &profile.Age)
        checkError(err)
        fmt.Println(profile)
    }
    rows.Close()
    db.Close()
}

func checkError(err error) {
    if (err != nil) {
        panic(err)
    }
}

Recommended Today

PHP realizes UnionPay business H5 payment

UnionPay business H5 payment interface document: document address 1: H5 payment interface address: 1: Alipay payment Test address: http://58.247.0.18:29015/v1/netpay/trade/h5-pay Official address: https://api-mop.chinaums.com/ 2: UnionPay payment Test address: http://58.247.0.18:29015/v1/netpay/uac/order Official address: https://api-mop.chinaums.com/ 2: Basic parameters required by the interface The interface uses get parameters. After the interface parameters are directly put into the interface address, the […]