Skip to content

Commit

Permalink
feat: add appender example
Browse files Browse the repository at this point in the history
  • Loading branch information
marcboeker committed Jul 18, 2024
1 parent fe93a2c commit 209fa2c
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
50 changes: 50 additions & 0 deletions examples/appender.go
Original file line number Diff line number Diff line change
@@ -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)
}

0 comments on commit 209fa2c

Please sign in to comment.