Last active
March 7, 2019 01:05
-
-
Save ismiyati/21eccd71cc949223bf6c0fa778c91fe2 to your computer and use it in GitHub Desktop.
coba postgre SQL stored procedure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "database/sql" | |
| "fmt" | |
| _ "github.com/lib/pq" | |
| ) | |
| func main() { | |
| defer func() { | |
| err := recover() | |
| if err != nil { | |
| fmt.Println(err) | |
| } | |
| }() | |
| db, err := sql.Open("postgres", "host=localhost port=5432 user=postgres password=p4ssw0rd dbname=postgres sslmode=disable") | |
| if err != nil { | |
| panic(err) | |
| } | |
| defer db.Close() | |
| _, err = db.Exec("DROP TABLE IF EXISTS tbl1") | |
| if err != nil { | |
| panic(err) | |
| } | |
| _, err = db.Exec(` | |
| CREATE TABLE tbl1( | |
| id SERIAL, | |
| fld1 TEXT, | |
| PRIMARY KEY (id) | |
| ) | |
| `) | |
| if err != nil { | |
| panic(err) | |
| } | |
| _, err = db.Exec("INSERT INTO tbl1(fld1) VALUES ('abc'), ('def'), ('ghi'), ('jkl')") | |
| if err != nil { | |
| panic(err) | |
| } | |
| _, err = db.Exec(` | |
| CREATE OR REPLACE PROCEDURE proc1(INT, INOUT id INT, INOUT fld1 TEXT) | |
| AS $$ | |
| BEGIN | |
| SELECT * INTO id, fld1 FROM tbl1 WHERE tbl1.id = $1; | |
| END; | |
| $$ LANGUAGE plpgsql; | |
| `) | |
| if err != nil { | |
| panic(err) | |
| } | |
| type Tbl1 struct { | |
| Id int | |
| Fld1 string | |
| } | |
| var rslt Tbl1 | |
| id := 4 | |
| err = db.QueryRow("CALL proc1($1, 0, '')", id).Scan(&rslt.Id, &rslt.Fld1) | |
| if err != nil { | |
| panic(err) | |
| } | |
| fmt.Printf("%v\n", rslt) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
