golangを使った、postgresqlのinsertの方法
/*
こんな感じで、DBとTableを作りました
create database agent_db;
create table LocMessage(
ID int,
Lat double precision,
Lng double precision,
TYPE varchar(10),
POPUP int,
RealId int,
PersonState int,
BikeState int,
StartStationLat double precision,
StartStationLng double precision,
GoalStationLat double precision,
GoalStationLng double precision,
StartStationName varchar(40),
GoalStationName varchar(40)
);
ちなみに、全部小文字になるみたいですねえ。
agent_db=# select * from locmessage;
id | lat | lng | type | popup | realid | personstate | bikestate | startstationlat | startstationlng | goalstationlat | goalstationlng | startstationname | goalstationname
----+--------+-------+----------+-------+--------+-------------+-----------+-----------------+-----------------+----------------+----------------+------------------+-----------------
*/
package main
import (
"database/sql"
"log"
_ "github.com/lib/pq"
)
func main() {
db, err := sql.Open("postgres",
"user=postgres password=password host=localhost port=15432 dbname=agent_db sslmode=disable")
if err != nil {
log.Fatal("OpenError: ", err)
}
defer db.Close()
//_, err = db.Exec("insert into locmessage(id,lat,lng,type,popup,realid,startstationlng ) VALUES(1, 139.0, 38.0, 'PERSON',1,1,222.222);")
// _, err = db.Exec("insert into locmessage(id,lat) VALUES(a, b);")
//ins, err := db.Prepare("insert into locmessage(id,lat,lng,type,popup,realid,startstationlng ) VALUES(?,?,?,?,?,?,?)")
ins, err := db.Prepare("insert into locmessage(id,lat,lng,type,popup,realid,startstationlng ) VALUES($1,$2,$3,$4,$5,$6,$7)")
if err != nil {
log.Fatal("db.Exec Error: ", err)
}
a := 1
b := 139.02
c := 38.02
dd := "Tomoichi"
e := 1
f := 1
g := 333.333
//ins.Exec("1", "139.0", "38.0", "BIKE", "1", "1", "222.222")
//ins.Exec(1, 139.01, 38.01, "BIKE", 1, 1, 222.222)
//ins.Exec(1, 139.0, 38.0, 1, 1, 1, 222.222)
ins.Exec(a, b, c, dd, e, f, g)
}
とりあえず、これでデータベースの書き込みはできるみたい。