main.go 2.2 KB
Newer Older
1 2 3 4 5 6
package main

import (
	"fmt"
	"time"

T
t_max 已提交
7 8 9
	"github.com/taosdata/driver-go/v3/af"
	"github.com/taosdata/driver-go/v3/af/param"
	"github.com/taosdata/driver-go/v3/common"
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
)

func checkErr(err error, prompt string) {
	if err != nil {
		fmt.Printf("%s\n", prompt)
		panic(err)
	}
}

func prepareStable(conn *af.Connector) {
	_, err := conn.Exec("CREATE DATABASE power")
	checkErr(err, "failed to create database")
	_, err = conn.Exec("CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)")
	checkErr(err, "failed to create stable")
	_, err = conn.Exec("USE power")
	checkErr(err, "failed to change database")
}

func main() {
	conn, err := af.Open("localhost", "root", "taosdata", "", 6030)
	checkErr(err, "fail to connect")
	defer conn.Close()
	prepareStable(conn)
	// create stmt
	stmt := conn.InsertStmt()
	defer stmt.Close()
	err = stmt.Prepare("INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)")
	checkErr(err, "failed to create prepare statement")

	// bind table name and tags
D
dingbo 已提交
40
	tagParams := param.NewParam(2).AddBinary([]byte("California.SanFrancisco")).AddInt(2)
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
	err = stmt.SetTableNameWithTags("d1001", tagParams)
	checkErr(err, "failed to execute SetTableNameWithTags")

	// specify ColumnType
	var bindType *param.ColumnType = param.NewColumnType(4).AddTimestamp().AddFloat().AddInt().AddFloat()

	// bind values. note: can only bind one row each time.
	valueParams := []*param.Param{
		param.NewParam(1).AddTimestamp(time.Unix(1648432611, 249300000), common.PrecisionMilliSecond),
		param.NewParam(1).AddFloat(10.3),
		param.NewParam(1).AddInt(219),
		param.NewParam(1).AddFloat(0.31),
	}
	err = stmt.BindParam(valueParams, bindType)
	checkErr(err, "BindParam error")
	err = stmt.AddBatch()
	checkErr(err, "AddBatch error")

	// bind one more row
	valueParams = []*param.Param{
		param.NewParam(1).AddTimestamp(time.Unix(1648432611, 749300000), common.PrecisionMilliSecond),
		param.NewParam(1).AddFloat(12.6),
		param.NewParam(1).AddInt(218),
		param.NewParam(1).AddFloat(0.33),
	}
	err = stmt.BindParam(valueParams, bindType)
	checkErr(err, "BindParam error")
	err = stmt.AddBatch()
	checkErr(err, "AddBatch error")
	// execute
	err = stmt.Execute()
	checkErr(err, "Execute batch error")
}