从数据库中读取数据

personal.db
package main

import (
    "database/sql"
    "fmt"

    _ "github.com/mattn/go-sqlite3"
)
// 用struct类型将来自sql数据库的数据映射到内存中的对象
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可以使用参数
    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)
    }
}

将数据插入数据库

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)
    /* 更新数据库数据
    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)
    /* 删除数据库数据
    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)
    }
}