Skip to content

Instantly share code, notes, and snippets.

@aalmiray

aalmiray/app.go

Last active Jul 1, 2020
Embed
What would you like to do?
OJDBC + Go sqlx
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
You can’t perform that action at this time.