LoginSignup
3
3

More than 3 years have passed since last update.

Golangのデータベース操作を雑多にまとめる

Last updated at Posted at 2020-02-21

本当に雑多に走り書き、DBはsqlite3を用いる。

テーブルの作成

func main() {
    DbConnection,  _ := sql.Open("sqlite3", "./data.sql")
    defer DbConnection.Close()
    cmd := `CREATE TABLE IF NOT EXISTS person(
                name STRING,
                age INT)`
    _, err := DbConnection.Exec(cmd)
    if err != nil {
        log.Fatalln(err)
    }
}

テーブルに挿入


func main() {
    DbConnection := sql.Open("sqlite3", "./data.sql")
    defer DbConnection.Close()
    cmd := "INSERT INTO person (name age) VALUES (?, ?)"
    _, err := DbConnection.Exec(cmd, "Nancy", 24)
    if err != nil {
        log.Fatalln(err)
    }
}

テーブルを更新


func main() {
    DbConnection := sql.Open("sqlite3", "./data.sql")
    defer DbConnection.Close()
    cmd := "UPDATE person SET age = ? WHERE user_id = ?"
    _, err := DbConnection.Exec(cmd, "1234)
    if err != nil {
        log.Fatalln(err)
    }
}

テーブルからMultiple Selectし、結果をPerson構造体のスライスに詰める

DbConnection.Queryを使い、結果をrows.Next()でループを回す


type Person struct {
    Name string
    Age int
}

func main() {
    DbConnection := sql.Open("sqlite3", "./data.sql")
    defer DbConnection.Close()

    cmd := "SELECT * FROM person WHERE"
    rows, _ := DbConnection.Query(cmd)

    var persons []Person
    for rows.Next() {
        var p Person
        err := rows.Scan(&p.Name, &p.Age)
        if err != nil {
            log.Println(err)
        }
        persons = append(persons, p)
    }
}

テーブルからSingle Selectし、結果をPerson構造体にする

DbConnection.QueryRowを使う。

func main() {
    DbConnection := sql.Open("sqlite3", "./data.sql")
    defer DbConnection.Close()

    cmd := "SELECT * FROM person WHERE age = ?"
    row := DbConnection.QueryRow(cmd, 28)

    var Person p
    err := row.Scan(&p.Name, &p.Age)

    if err != nil {
        // 条件を満たすものが見つからない場合
        if err == sql.ErrNoRows {
            log.Println("No row")
        // そういうわけではないがエラー
        log.Println(err)
    }
}

テーブルからデータを削除

func main() {
    DbConnection := sql.Open("sqlite3", "./data.sql")
    defer DbConnection.Close()

    cmd := "DELETE FROM person WHERE user_id = ?"
    row := DbConnection.Exec(cmd, 1234)

    if err != nil {
        log.Fatalln(err)
    }
}

クエリインジェクション対策

  • valueは?でエスケープする
  • ただし、table名は?で挿入できず、%sをplaceholderとする
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3