Sqlite3 db insert

This commit is contained in:
William Clark 2023-11-23 12:39:49 +00:00
parent 14f7c13021
commit 01ab06fbf0
2 changed files with 22 additions and 5 deletions

View File

@ -2,7 +2,7 @@
[TH7]
port = 9090 # web port
debug = true # enable to use simulated PCB for development
nolog = true
nolog = false
# all DB settings are individual to each DB
[DB]

View File

@ -4,8 +4,10 @@ import (
"database/sql"
"errors"
"fmt"
"log"
"sync"
"th7/data/core"
"time"
_ "github.com/mattn/go-sqlite3"
)
@ -36,8 +38,6 @@ func NewSQLite3Adapter(dbInfo map[string]interface{}) (*SQLite3Adapter, error) {
const create string = `
CREATE TABLE IF NOT EXISTS logs (
id INTEGER NOT NULL,
type TEXT NOT NULL,
unit TEXT NOT NULL,
value REAL NOT NULL,
timestamp TEXT NOT NULL
);`
@ -53,10 +53,27 @@ func (ad *SQLite3Adapter) Close() {
ad.db.Close()
}
func (ad *SQLite3Adapter) Save([]core.Channel) error {
func (ad *SQLite3Adapter) Save(channels []core.Channel) error {
ad.mu.Lock()
defer ad.mu.Unlock()
fmt.Println("TODO save data...")
insertLogSQL := `INSERT INTO logs (id, value, timestamp) VALUES (?, ?, ?)`
statement, err := ad.db.Prepare(insertLogSQL)
if err != nil {
log.Fatalln(err.Error())
}
timestamp := time.Now().Format(time.RFC1123)
for c := range channels {
_, err = statement.Exec(channels[c].Id, channels[c].Value, timestamp)
if err != nil {
log.Fatalln(err.Error())
}
fmt.Printf("[%s] INSERTED id=%d value=%f\n", timestamp, channels[c].Id, channels[c].Value)
}
return nil
}