データベース作成
INSERT
package main
import (
"database/sql"
"log"
_ "github.com/mattn/go-sqLite3"
)
var DbConnection *sql.DB
func main() {
DbConnection, _ := sql.Open("sqlite3", "./example.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)
}
// レコードINSERT
cmd = "INSERT INTO person (name, age) VALUES (?, ?)"
_, err = DbConnection.Exec(cmd, "Nancy", 20)
if err != nil {
log.Fatalln(err)
}
}
PS C:\Users\yuta\go\src\semaphore> sqlite3 .\example.sql
SQLite version 3.32.3 2020-06-18 14:00:33
Enter ".help" for usage hints.
sqlite> .table
person
sqlite>
sqlite> select * from person;
Nancy|20
SELECT
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/mattn/go-sqLite3"
)
var DbConnection *sql.DB
type Person struct {
Name string
Age int
}
func main() {
DbConnection, _ := sql.Open("sqlite3", "./example.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)
}
// レコードINSERT
cmd = "SELECT * FROM person where age = ?"
row := DbConnection.QueryRow(cmd, 20)
var p Person
err = row.Scan(&p.Name, &p.Age)
if err != nil {
if err == sql.ErrNoRows {
log.Println("No row")
} else {
log.Println(err)
}
}
fmt.Println(p.Name, p.Age)
}
Nancy 20
### DELETE
```golang
package main
import (
"database/sql"
"log"
_ "github.com/mattn/go-sqLite3"
)
var DbConnection *sql.DB
type Person struct {
Name string
Age int
}
func main() {
DbConnection, _ := sql.Open("sqlite3", "./example.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)
}
// レコードDELETE
cmd = "DELETE FROM person WHERE name = ?"
_, err = DbConnection.Exec(cmd, "Nancy")
if err != nil {
log.Fatalln(err)
}
}
教材