/
main.go
89 lines (72 loc) · 2.15 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// SPDX-FileCopyrightText: 2020 SAP SE
// SPDX-FileCopyrightText: 2021 SAP SE
// SPDX-FileCopyrightText: 2022 SAP SE
// SPDX-FileCopyrightText: 2023 SAP SE
//
// SPDX-License-Identifier: Apache-2.0
// This example shows a simple interaction with a TDS server using the
// database/sql interface and the cgo-based driver.
package main
import (
"database/sql"
"fmt"
"log"
"math"
"os"
"github.com/SAP/cgo-ase"
"github.com/SAP/go-dblib/dsn"
)
func main() {
if err := DoMain(); err != nil {
log.Printf("Failed: %v", err)
os.Exit(1)
}
}
func DoMain() error {
info, err := ase.NewInfoWithEnv()
if err != nil {
return fmt.Errorf("error reading DSN info from env: %w", err)
}
fmt.Println("Opening database")
db, err := sql.Open("ase", dsn.FormatSimple(info))
if err != nil {
return fmt.Errorf("failed to open connection to database: %w", err)
}
defer db.Close()
if _, err := db.Exec("if object_id('simple_tab') is not null drop table simple_tab"); err != nil {
return fmt.Errorf("failed to drop table 'simple_tab': %w", err)
}
fmt.Println("Creating table 'simple_tab'")
if _, err := db.Exec("create table simple_tab (a int, b char(30))"); err != nil {
return fmt.Errorf("failed to create table: %w", err)
}
fmt.Printf("Writing a=%d, b='a string' to table\n", math.MaxInt32)
if _, err := db.Exec("insert into simple_tab (a, b) values (?, ?)", math.MaxInt32, "a string"); err != nil {
return fmt.Errorf("failed to insert values: %w", err)
}
fmt.Println("Querying values from table")
rows, err := db.Query("select * from simple_tab")
if err != nil {
return fmt.Errorf("querying failed: %w", err)
}
defer rows.Close()
fmt.Println("Displaying results of query")
colNames, err := rows.Columns()
if err != nil {
return fmt.Errorf("failed to retrieve column names: %w", err)
}
fmt.Printf("| %-10s | %-30s |\n", colNames[0], colNames[1])
format := "| %-10d | %-30s |\n"
var a int
var b string
for rows.Next() {
if err := rows.Scan(&a, &b); err != nil {
return fmt.Errorf("failed to scan row: %w", err)
}
fmt.Printf(format, a, b)
}
if err := rows.Err(); err != nil {
return fmt.Errorf("error reading rows: %w", err)
}
return nil
}