From 209fa2c6c4eb926dbfd17739b6a760ed3b33c6b5 Mon Sep 17 00:00:00 2001 From: Marc Boeker Date: Thu, 18 Jul 2024 23:02:17 +0200 Subject: [PATCH] feat: add appender example --- README.md | 2 +- examples/appender.go | 50 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 examples/appender.go diff --git a/README.md b/README.md index 65b71dc3..3bc67021 100644 --- a/README.md +++ b/README.md @@ -100,7 +100,7 @@ defer connector.Close() ## DuckDB Appender API -If you want to use the [DuckDB Appender API](https://duckdb.org/docs/data/appender.html), you can obtain a new `Appender` by passing a DuckDB connection to `NewAppenderFromConn()`. +If you want to use the [DuckDB Appender API](https://duckdb.org/docs/data/appender.html), you can obtain a new `Appender` by passing a DuckDB connection to `NewAppenderFromConn()`. See `examples/appender.go` for a complete example. ```go connector, err := duckdb.NewConnector("test.db", nil) diff --git a/examples/appender.go b/examples/appender.go new file mode 100644 index 00000000..85bf8b0b --- /dev/null +++ b/examples/appender.go @@ -0,0 +1,50 @@ +package main + +import ( + "context" + "database/sql" + "log" + + "github.com/marcboeker/go-duckdb" +) + +func main() { + c, err := duckdb.NewConnector("", nil) + if err != nil { + log.Fatalf("could not initialize new connector: %s", err.Error()) + } + + con, err := c.Connect(context.Background()) + if err != nil { + log.Fatalf("could not connect: %s", err.Error()) + } + + db := sql.OpenDB(c) + if _, err := db.Exec(`CREATE TABLE users (name VARCHAR, age INTEGER)`); err != nil { + log.Fatalf("could not create table users: %s", err.Error()) + } + + a, err := duckdb.NewAppenderFromConn(con, "", "users") + if err != nil { + log.Fatalf("could not create new appender for users: %s", err.Error()) + } + + if err := a.AppendRow("Fred", int32(34)); err != nil { + log.Fatalf("could not append row to users: %s", err.Error()) + } + + if err := a.Close(); err != nil { + log.Fatalf("could not flush and close appender: %s", err.Error()) + } + + var ( + name string + age int + ) + row := db.QueryRowContext(context.Background(), `SELECT name, age FROM users`) + if err := row.Scan(&name, &age); err != nil { + log.Fatalf("could not retrieve user from db: %s", err.Error()) + } + + log.Printf("User: name=%s, age=%d", name, age) +}