main.go 1.7 KB
Newer Older
B
Bo Ding 已提交
1 2 3 4 5
package main

import (
	"database/sql"
	"fmt"
6
	"log"
B
Bo Ding 已提交
7

T
t_max 已提交
8
	_ "github.com/taosdata/driver-go/v3/taosRestful"
B
Bo Ding 已提交
9 10 11 12 13
)

func createStable(taos *sql.DB) {
	_, err := taos.Exec("CREATE DATABASE power")
	if err != nil {
14
		log.Fatalln("failed to create database, err:", err)
B
Bo Ding 已提交
15 16 17
	}
	_, err = taos.Exec("CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)")
	if err != nil {
18
		log.Fatalln("failed to create stable, err:", err)
B
Bo Ding 已提交
19 20 21 22
	}
}

func insertData(taos *sql.DB) {
23 24 25 26
	sql := `INSERT INTO power.d1001 USING power.meters TAGS('California.SanFrancisco', 2) VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000) ('2018-10-03 14:38:15.000', 12.60000, 218, 0.33000) ('2018-10-03 14:38:16.800', 12.30000, 221, 0.31000)
	power.d1002 USING power.meters TAGS('California.SanFrancisco', 3) VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000)
	power.d1003 USING power.meters TAGS('California.LosAngeles', 2) VALUES ('2018-10-03 14:38:05.500', 11.80000, 221, 0.28000) ('2018-10-03 14:38:16.600', 13.40000, 223, 0.29000)
	power.d1004 USING power.meters TAGS('California.LosAngeles', 3) VALUES ('2018-10-03 14:38:05.000', 10.80000, 223, 0.29000) ('2018-10-03 14:38:06.500', 11.50000, 221, 0.35000)`
B
Bo Ding 已提交
27 28
	result, err := taos.Exec(sql)
	if err != nil {
29
		log.Fatalln("failed to insert, err:", err)
B
Bo Ding 已提交
30 31 32
	}
	rowsAffected, err := result.RowsAffected()
	if err != nil {
33
		log.Fatalln("failed to get affected rows, err:", err)
B
Bo Ding 已提交
34 35 36 37 38 39 40 41
	}
	fmt.Println("RowsAffected", rowsAffected)
}

func main() {
	var taosDSN = "root:taosdata@http(localhost:6041)/"
	taos, err := sql.Open("taosRestful", taosDSN)
	if err != nil {
42
		log.Fatalln("failed to connect TDengine, err:", err)
B
Bo Ding 已提交
43 44 45 46 47
	}
	defer taos.Close()
	createStable(taos)
	insertData(taos)
}