Last active
July 1, 2020 15:24
-
-
Save aalmiray/9ca9fd306bec015750c4e5ee0334daae to your computer and use it in GitHub Desktop.
OJDBC + Go sqlx
This file contains 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 ( | |
"fmt" | |
"log" | |
_ "github.com/godror/godror" | |
"github.com/jmoiron/sqlx" | |
) | |
var schema = ` | |
DECLARE | |
v_ddl CONSTANT VARCHAR2(4000) := | |
'CREATE TABLE TODOS | |
( | |
id NUMBER GENERATED ALWAYS AS IDENTITY NOT NULL PRIMARY KEY, | |
description VARCHAR(255) NOT NULL, | |
done NUMBER(1,0) NOT NULL | |
) | |
'; | |
BEGIN | |
EXECUTE IMMEDIATE v_ddl; | |
END;` | |
type Todo struct { | |
Id int `db:"ID"` | |
Description string `db:"DESCRIPTION"` | |
Done bool `db:"DONE"` | |
} | |
func main() { | |
username := "dbusername" | |
password := "S3cr#tP4$sW0rD" | |
db, err := sqlx.Connect("godror", username+"/"+password+"@localhost:51521/XE") | |
if err != nil { | |
log.Fatalln(err) | |
} | |
db.MustExec(schema) | |
tx := db.MustBegin() | |
tx.MustExec("INSERT INTO TODOS (description, done) VALUES (:description, :done)", "Demo code", 1) | |
tx.MustExec("INSERT INTO TODOS (description, done) VALUES (:description, :done)", "Blog post", 0) | |
tx.Commit() | |
// load all rows | |
todos := []Todo{} | |
db.Select(&todos, "SELECT * FROM TODOS ORDER BY id ASC") | |
demo, blog := todos[0], todos[1] | |
fmt.Printf("%#v\n%#v\n", demo, blog) | |
// load each row separately | |
todo := Todo{} | |
rows, err := db.Queryx("SELECT * FROM TODOS") | |
for rows.Next() { | |
err := rows.StructScan(&todo) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
fmt.Printf("%#v\n", todo) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment