Merge branch '3.0' of https://github.com/taosdata/TDengine into feature/data_format
This commit is contained in:
commit
e35d01dcc1
|
@ -71,8 +71,8 @@ ELSE ()
|
|||
ENDIF ()
|
||||
|
||||
IF (${SANITIZER} MATCHES "true")
|
||||
SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror -Werror=return-type -fPIC -gdwarf-2 -fsanitize=address -fsanitize=undefined -fno-sanitize-recover=all -fsanitize=float-divide-by-zero -fsanitize=float-cast-overflow -fno-sanitize=null -fno-sanitize=alignment -static-libasan -g3")
|
||||
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror -Wno-literal-suffix -Werror=return-type -fPIC -gdwarf-2 -fsanitize=address -fsanitize=undefined -fno-sanitize-recover=all -fsanitize=float-divide-by-zero -fsanitize=float-cast-overflow -fno-sanitize=null -fno-sanitize=alignment -static-libasan -g3")
|
||||
SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror -Werror=return-type -fPIC -gdwarf-2 -fsanitize=address -fsanitize=undefined -fsanitize-recover=all -fsanitize=float-divide-by-zero -fsanitize=float-cast-overflow -fno-sanitize=null -fno-sanitize=alignment -static-libasan -g3")
|
||||
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror -Wno-literal-suffix -Werror=return-type -fPIC -gdwarf-2 -fsanitize=address -fsanitize=undefined -fsanitize-recover=all -fsanitize=float-divide-by-zero -fsanitize=float-cast-overflow -fno-sanitize=null -fno-sanitize=alignment -static-libasan -g3")
|
||||
MESSAGE(STATUS "Will compile with Address Sanitizer!")
|
||||
ELSE ()
|
||||
SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror -Werror=return-type -fPIC -gdwarf-2 -g3")
|
||||
|
|
|
@ -146,5 +146,6 @@ option(
|
|||
option(
|
||||
BUILD_WITH_INVERTEDINDEX
|
||||
"If use invertedIndex"
|
||||
ON
|
||||
OFF
|
||||
)
|
||||
|
||||
|
|
|
@ -33,7 +33,7 @@ TDengine 提供了丰富的应用程序开发接口,为了便于用户快速
|
|||
关键不同点在于:
|
||||
|
||||
1. 使用 REST 连接,用户无需安装客户端驱动程序 taosc,具有跨平台易用的优势,但性能要下降 30%左右。
|
||||
2. 使用原生连接可以体验 TDengine 的全部功能,如[参数绑定接口](/reference/connector/cpp#参数绑定-api)、[订阅](reference/connector/cpp#数据订阅接口)等等。
|
||||
2. 使用原生连接可以体验 TDengine 的全部功能,如[参数绑定接口](/reference/connector/cpp#参数绑定-api)、[订阅](/reference/connector/cpp#订阅和消费-api)等等。
|
||||
|
||||
## 安装客户端驱动 taosc
|
||||
|
||||
|
|
|
@ -20,21 +20,21 @@ CREATE DATABASE [IF NOT EXISTS] db_name [KEEP keep] [DAYS days] [UPDATE 1];
|
|||
3. 数据库名最大长度为 33;
|
||||
4. 一条 SQL 语句的最大长度为 65480 个字符;
|
||||
5. 创建数据库时可用的参数有:
|
||||
- cache: [Description](/reference/config/#cache)
|
||||
- blocks: [Description](/reference/config/#blocks)
|
||||
- days: [Description](/reference/config/#days)
|
||||
- keep: [Description](/reference/config/#keep)
|
||||
- minRows: [Description](/reference/config/#minrows)
|
||||
- maxRows: [Description](/reference/config/#maxrows)
|
||||
- wal: [Description](/reference/config/#wallevel)
|
||||
- fsync: [Description](/reference/config/#fsync)
|
||||
- update: [Description](/reference/config/#update)
|
||||
- cacheLast: [Description](/reference/config/#cachelast)
|
||||
- replica: [Description](/reference/config/#replica)
|
||||
- quorum: [Description](/reference/config/#quorum)
|
||||
- maxVgroupsPerDb: [Description](/reference/config/#maxvgroupsperdb)
|
||||
- comp: [Description](/reference/config/#comp)
|
||||
- precision: [Description](/reference/config/#precision)
|
||||
- cache: [详细说明](/reference/config/#cache)
|
||||
- blocks: [详细说明](/reference/config/#blocks)
|
||||
- days: [详细说明](/reference/config/#days)
|
||||
- keep: [详细说明](/reference/config/#keep)
|
||||
- minRows: [详细说明](/reference/config/#minrows)
|
||||
- maxRows: [详细说明](/reference/config/#maxrows)
|
||||
- wal: [详细说明](/reference/config/#wallevel)
|
||||
- fsync: [详细说明](/reference/config/#fsync)
|
||||
- update: [详细说明](/reference/config/#update)
|
||||
- cacheLast: [详细说明](/reference/config/#cachelast)
|
||||
- replica: [详细说明](/reference/config/#replica)
|
||||
- quorum: [详细说明](/reference/config/#quorum)
|
||||
- maxVgroupsPerDb: [详细说明](/reference/config/#maxvgroupsperdb)
|
||||
- comp: [详细说明](/reference/config/#comp)
|
||||
- precision: [详细说明](/reference/config/#precision)
|
||||
6. 请注意上面列出的所有参数都可以配置在配置文件 `taosd.cfg` 中作为创建数据库时使用的默认配置, `create database` 的参数中明确指定的会覆盖配置文件中的设置。
|
||||
|
||||
:::
|
||||
|
|
|
@ -33,7 +33,7 @@ Either way, same or similar APIs are provided by connectors to access database o
|
|||
Key differences:
|
||||
|
||||
1. With REST connection, it's not necessary to install TDengine client driver (taosc), it's more friendly for cross-platform with the cost of 30% performance downgrade. When taosc has an upgrade, application does not need to make changes.
|
||||
2. With native connection, full compatibility of TDengine can be utilized, like [Parameter Binding](/reference/connector/cpp#Parameter Binding-api), [Subscription](reference/connector/cpp#Subscription), etc. But taosc has to be installed, some platforms may not be supported.
|
||||
2. With native connection, full compatibility of TDengine can be utilized, like [Parameter Binding](/reference/connector/cpp#parameter-binding-api), [Subscription](/reference/connector/cpp#subscription-and-consumption-api), etc. But taosc has to be installed, some platforms may not be supported.
|
||||
|
||||
## Install Client Driver taosc
|
||||
|
||||
|
|
|
@ -34,7 +34,7 @@ CREATE DATABASE [IF NOT EXISTS] db_name [KEEP keep] [DAYS days] [UPDATE 1];
|
|||
- quorum: [Description](/reference/config/#quorum)
|
||||
- maxVgroupsPerDb: [Description](/reference/config/#maxvgroupsperdb)
|
||||
- comp: [Description](/reference/config/#comp)
|
||||
- precision: [Description](reference/config/#precision)
|
||||
- precision: [Description](/reference/config/#precision)
|
||||
6. Please be noted that all of the parameters mentioned in this section can be configured in configuration file `taosd.cfg` at server side and used by default, can be override if they are specified in `create database` statement.
|
||||
|
||||
:::
|
||||
|
|
|
@ -78,7 +78,7 @@ Manually install the following tools.
|
|||
- Install [Python](https://www.python.org/downloads/) 2.7 (`v3.x.x` is not supported) and execute `npm config set python python2.7`.
|
||||
- Go to the `cmd` command-line interface, `npm config set msvs_version 2017`
|
||||
|
||||
Refer to Microsoft's Node.js User Manual [Microsoft's Node.js Guidelines for Windows](https://github.com/Microsoft/nodejs-guidelines/blob/master/windows- environment. md#compiling-native-addon-modules).
|
||||
Refer to Microsoft's Node.js User Manual [Microsoft's Node.js Guidelines for Windows](https://github.com/Microsoft/nodejs-guidelines/blob/master/windows-environment.md#compiling-native-addon-modules).
|
||||
|
||||
If using ARM64 Node.js on Windows 10 ARM, you must add "Visual C++ compilers and libraries for ARM64" and "Visual C++ ATL for ARM64".
|
||||
|
||||
|
|
|
@ -32,7 +32,7 @@ We will explain how to migrate OpenTSDB applications to TDengine quickly, secure
|
|||
The following figure (Figure 1) shows the system's overall architecture for a typical DevOps application scenario.
|
||||
|
||||
**Figure 1. Typical architecture in a DevOps scenario**
|
||||
Figure 1. [IT-DevOps-Solutions-Immigrate-OpenTSDB-Arch](/img/IT-DevOps-Solutions-Immigrate-OpenTSDB-Arch.jpg "Figure 1. Typical architecture in a DevOps scenario")
|
||||

|
||||
|
||||
In this application scenario, there are Agent tools deployed in the application environment to collect machine metrics, network metrics, and application metrics. Data collectors to aggregate information collected by agents, systems for persistent data storage and management, and tools for monitoring data visualization (e.g., Grafana, etc.).
|
||||
|
||||
|
@ -75,7 +75,7 @@ After writing the data to TDengine properly, you can adapt Grafana to visualize
|
|||
TDengine provides two sets of Dashboard templates by default, and users only need to import the templates from the Grafana directory into Grafana to activate their use.
|
||||
|
||||
**Importing Grafana Templates** Figure 2.
|
||||
! [](/img/IT-DevOps-Solutions-Immigrate-OpenTSDB-Dashboard.jpg "Figure 2. Importing a Grafana Template")
|
||||

|
||||
|
||||
After the above steps, you completed the migration to replace OpenTSDB with TDengine. You can see that the whole process is straightforward, there is no need to write any code, and only some configuration files need to be adjusted to meet the migration work.
|
||||
|
||||
|
@ -88,7 +88,7 @@ In most DevOps scenarios, if you have a small OpenTSDB cluster (3 or fewer nodes
|
|||
Suppose your application is particularly complex, or the application domain is not a DevOps scenario. You can continue reading subsequent chapters for a more comprehensive and in-depth look at the advanced topics of migrating an OpenTSDB application to TDengine.
|
||||
|
||||
**Figure 3. System architecture after migration**
|
||||
! [IT-DevOps-Solutions-Immigrate-TDengine-Arch](/img/IT-DevOps-Solutions-Immigrate-TDengine-Arch.jpg "Figure 3. System architecture after migration completion")
|
||||

|
||||
|
||||
## Migration evaluation and strategy for other scenarios
|
||||
|
||||
|
@ -96,7 +96,7 @@ Suppose your application is particularly complex, or the application domain is n
|
|||
|
||||
This chapter describes the differences between OpenTSDB and TDengine at the system functionality level. After reading this chapter, you can fully evaluate whether you can migrate some complex OpenTSDB-based applications to TDengine, and what you should pay attention to after migration.
|
||||
|
||||
TDengine currently only supports Grafana for visual kanban rendering, so if your application uses front-end kanban boards other than Grafana (e.g., [TSDash](https://github.com/facebook/tsdash), [Status Wolf](https://github) .com/box/StatusWolf), etc.). You cannot directly migrate those front-end kanbans to TDengine, and the front-end kanban will need to be ported to Grafana to work correctly.
|
||||
TDengine currently only supports Grafana for visual kanban rendering, so if your application uses front-end kanban boards other than Grafana (e.g., [TSDash](https://github.com/facebook/tsdash), [Status Wolf](https://github.com/box/StatusWolf), etc.). You cannot directly migrate those front-end kanbans to TDengine, and the front-end kanban will need to be ported to Grafana to work correctly.
|
||||
|
||||
TDengine version 2.3.0.x only supports collectd and StatsD as data collection aggregation software but will provide more data collection aggregation software in the future. If you use other data aggregators on the collection side, your application needs to be ported to these two data aggregation systems to write data correctly.
|
||||
In addition to the two data aggregator software protocols mentioned above, TDengine also supports writing data directly via InfluxDB's line protocol and OpenTSDB's data writing protocol, JSON format. You can rewrite the logic on the data push side to write data using the line protocols supported by TDengine.
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
.vscode
|
||||
*.lock
|
||||
.idea
|
|
@ -0,0 +1,2 @@
|
|||
.vscode
|
||||
*.lock
|
|
@ -0,0 +1,16 @@
|
|||
if (! "RJDBC" %in% installed.packages()[, "Package"]) {
|
||||
install.packages('RJDBC', repos='http://cran.us.r-project.org')
|
||||
}
|
||||
|
||||
# ANCHOR: demo
|
||||
library("DBI")
|
||||
library("rJava")
|
||||
library("RJDBC")
|
||||
|
||||
args<- commandArgs(trailingOnly = TRUE)
|
||||
driver_path = args[1] # path to jdbc-driver for example: "/root/taos-jdbcdriver-2.0.37-dist.jar"
|
||||
driver = JDBC("com.taosdata.jdbc.TSDBDriver", driver_path)
|
||||
conn = dbConnect(driver, "jdbc:TAOS://127.0.0.1:6030/?user=root&password=taosdata")
|
||||
dbGetQuery(conn, "SELECT server_version()")
|
||||
dbDisconnect(conn)
|
||||
# ANCHOR_END: demo
|
|
@ -0,0 +1,12 @@
|
|||
if (! "RJDBC" %in% installed.packages()[, "Package"]) {
|
||||
install.packages('RJDBC', repos='http://cran.us.r-project.org')
|
||||
}
|
||||
|
||||
library("DBI")
|
||||
library("rJava")
|
||||
library("RJDBC")
|
||||
driver_path = "/home/debug/build/lib/taos-jdbcdriver-2.0.38-dist.jar"
|
||||
driver = JDBC("com.taosdata.jdbc.rs.RestfulDriver", driver_path)
|
||||
conn = dbConnect(driver, "jdbc:TAOS-RS://localhost:6041?user=root&password=taosdata")
|
||||
dbGetQuery(conn, "SELECT server_version()")
|
||||
dbDisconnect(conn)
|
|
@ -0,0 +1,3 @@
|
|||
*
|
||||
!*.c
|
||||
!.gitignore
|
|
@ -0,0 +1,195 @@
|
|||
// compile with:
|
||||
// gcc -o async_query_example async_query_example.c -ltaos
|
||||
|
||||
#include <inttypes.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/time.h>
|
||||
#include <taos.h>
|
||||
|
||||
typedef int16_t VarDataLenT;
|
||||
|
||||
#define TSDB_NCHAR_SIZE sizeof(int32_t)
|
||||
#define VARSTR_HEADER_SIZE sizeof(VarDataLenT)
|
||||
|
||||
#define GET_FLOAT_VAL(x) (*(float *)(x))
|
||||
#define GET_DOUBLE_VAL(x) (*(double *)(x))
|
||||
|
||||
#define varDataLen(v) ((VarDataLenT *)(v))[0]
|
||||
|
||||
int printRow(char *str, TAOS_ROW row, TAOS_FIELD *fields, int numFields) {
|
||||
int len = 0;
|
||||
char split = ' ';
|
||||
|
||||
for (int i = 0; i < numFields; ++i) {
|
||||
if (i > 0) {
|
||||
str[len++] = split;
|
||||
}
|
||||
|
||||
if (row[i] == NULL) {
|
||||
len += sprintf(str + len, "%s", "NULL");
|
||||
continue;
|
||||
}
|
||||
|
||||
switch (fields[i].type) {
|
||||
case TSDB_DATA_TYPE_TINYINT:
|
||||
len += sprintf(str + len, "%d", *((int8_t *)row[i]));
|
||||
break;
|
||||
|
||||
case TSDB_DATA_TYPE_UTINYINT:
|
||||
len += sprintf(str + len, "%u", *((uint8_t *)row[i]));
|
||||
break;
|
||||
|
||||
case TSDB_DATA_TYPE_SMALLINT:
|
||||
len += sprintf(str + len, "%d", *((int16_t *)row[i]));
|
||||
break;
|
||||
|
||||
case TSDB_DATA_TYPE_USMALLINT:
|
||||
len += sprintf(str + len, "%u", *((uint16_t *)row[i]));
|
||||
break;
|
||||
|
||||
case TSDB_DATA_TYPE_INT:
|
||||
len += sprintf(str + len, "%d", *((int32_t *)row[i]));
|
||||
break;
|
||||
|
||||
case TSDB_DATA_TYPE_UINT:
|
||||
len += sprintf(str + len, "%u", *((uint32_t *)row[i]));
|
||||
break;
|
||||
|
||||
case TSDB_DATA_TYPE_BIGINT:
|
||||
len += sprintf(str + len, "%" PRId64, *((int64_t *)row[i]));
|
||||
break;
|
||||
|
||||
case TSDB_DATA_TYPE_UBIGINT:
|
||||
len += sprintf(str + len, "%" PRIu64, *((uint64_t *)row[i]));
|
||||
break;
|
||||
|
||||
case TSDB_DATA_TYPE_FLOAT: {
|
||||
float fv = 0;
|
||||
fv = GET_FLOAT_VAL(row[i]);
|
||||
len += sprintf(str + len, "%f", fv);
|
||||
} break;
|
||||
|
||||
case TSDB_DATA_TYPE_DOUBLE: {
|
||||
double dv = 0;
|
||||
dv = GET_DOUBLE_VAL(row[i]);
|
||||
len += sprintf(str + len, "%lf", dv);
|
||||
} break;
|
||||
|
||||
case TSDB_DATA_TYPE_BINARY:
|
||||
case TSDB_DATA_TYPE_NCHAR: {
|
||||
int32_t charLen = varDataLen((char *)row[i] - VARSTR_HEADER_SIZE);
|
||||
memcpy(str + len, row[i], charLen);
|
||||
len += charLen;
|
||||
} break;
|
||||
|
||||
case TSDB_DATA_TYPE_TIMESTAMP:
|
||||
len += sprintf(str + len, "%" PRId64, *((int64_t *)row[i]));
|
||||
break;
|
||||
|
||||
case TSDB_DATA_TYPE_BOOL:
|
||||
len += sprintf(str + len, "%d", *((int8_t *)row[i]));
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return len;
|
||||
}
|
||||
|
||||
void printHeader(TAOS_RES *res) {
|
||||
int numFields = taos_num_fields(res);
|
||||
TAOS_FIELD *fields = taos_fetch_fields(res);
|
||||
char header[256] = {0};
|
||||
int len = 0;
|
||||
for (int i = 0; i < numFields; ++i) {
|
||||
len += sprintf(header + len, "%s ", fields[i].name);
|
||||
}
|
||||
puts(header);
|
||||
}
|
||||
|
||||
// ANCHOR: demo
|
||||
|
||||
/**
|
||||
* @brief call back function of taos_fetch_row_a
|
||||
*
|
||||
* @param param : the third parameter you passed to taos_fetch_row_a
|
||||
* @param res : pointer of TAOS_RES
|
||||
* @param numOfRow : number of rows fetched in this batch. will be 0 if there is no more data.
|
||||
* @return void*
|
||||
*/
|
||||
void *fetch_row_callback(void *param, TAOS_RES *res, int numOfRow) {
|
||||
printf("numOfRow = %d \n", numOfRow);
|
||||
int numFields = taos_num_fields(res);
|
||||
TAOS_FIELD *fields = taos_fetch_fields(res);
|
||||
TAOS *_taos = (TAOS *)param;
|
||||
if (numOfRow > 0) {
|
||||
for (int i = 0; i < numOfRow; ++i) {
|
||||
TAOS_ROW row = taos_fetch_row(res);
|
||||
char temp[256] = {0};
|
||||
printRow(temp, row, fields, numFields);
|
||||
puts(temp);
|
||||
}
|
||||
taos_fetch_rows_a(res, fetch_row_callback, _taos);
|
||||
} else {
|
||||
printf("no more data, close the connection.\n");
|
||||
taos_free_result(res);
|
||||
taos_close(_taos);
|
||||
taos_cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief callback function of taos_query_a
|
||||
*
|
||||
* @param param: the fourth parameter you passed to taos_query_a
|
||||
* @param res : the result set
|
||||
* @param code : status code
|
||||
* @return void*
|
||||
*/
|
||||
void *select_callback(void *param, TAOS_RES *res, int code) {
|
||||
printf("query callback ...\n");
|
||||
TAOS *_taos = (TAOS *)param;
|
||||
if (code == 0 && res) {
|
||||
printHeader(res);
|
||||
taos_fetch_rows_a(res, fetch_row_callback, _taos);
|
||||
} else {
|
||||
printf("failed to execute taos_query. error: %s\n", taos_errstr(res));
|
||||
taos_free_result(res);
|
||||
taos_close(_taos);
|
||||
taos_cleanup();
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
TAOS *taos = taos_connect("localhost", "root", "taosdata", "power", 6030);
|
||||
if (taos == NULL) {
|
||||
puts("failed to connect to server");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
// param one is the connection returned by taos_connect.
|
||||
// param two is the SQL to execute.
|
||||
// param three is the callback function.
|
||||
// param four can be any pointer. It will be passed to your callback function as the first parameter. we use taos
|
||||
// here, because we want to close it after getting data.
|
||||
taos_query_a(taos, "SELECT * FROM meters", select_callback, taos);
|
||||
sleep(1);
|
||||
}
|
||||
|
||||
// output:
|
||||
// query callback ...
|
||||
// ts current voltage phase location groupid
|
||||
// numOfRow = 8
|
||||
// 1538548685000 10.300000 219 0.310000 beijing.chaoyang 2
|
||||
// 1538548695000 12.600000 218 0.330000 beijing.chaoyang 2
|
||||
// 1538548696800 12.300000 221 0.310000 beijing.chaoyang 2
|
||||
// 1538548696650 10.300000 218 0.250000 beijing.chaoyang 3
|
||||
// 1538548685500 11.800000 221 0.280000 beijing.haidian 2
|
||||
// 1538548696600 13.400000 223 0.290000 beijing.haidian 2
|
||||
// 1538548685000 10.800000 223 0.290000 beijing.haidian 3
|
||||
// 1538548686500 11.500000 221 0.350000 beijing.haidian 3
|
||||
// numOfRow = 0
|
||||
// no more data, close the connection.
|
||||
// ANCHOR_END: demo
|
|
@ -0,0 +1,24 @@
|
|||
// compile with
|
||||
// gcc connect_example.c -o connect_example -ltaos
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include "taos.h"
|
||||
|
||||
int main() {
|
||||
const char *host = "localhost";
|
||||
const char *user = "root";
|
||||
const char *passwd = "taosdata";
|
||||
// if don't want to connect to a default db, set it to NULL or ""
|
||||
const char *db = NULL;
|
||||
uint16_t port = 0; // 0 means use the default port
|
||||
TAOS *taos = taos_connect(host, user, passwd, db, port);
|
||||
if (taos == NULL) {
|
||||
int errno = taos_errno(NULL);
|
||||
char *msg = taos_errstr(NULL);
|
||||
printf("%d, %s\n", errno, msg);
|
||||
} else {
|
||||
printf("connected\n");
|
||||
taos_close(taos);
|
||||
}
|
||||
taos_cleanup();
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
// compile with
|
||||
// gcc error_handle_example.c -o error_handle_example -ltaos
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include "taos.h"
|
||||
|
||||
int main() {
|
||||
const char *host = "localhost";
|
||||
const char *user = "root";
|
||||
const char *passwd = "taosdata";
|
||||
// if don't want to connect to a default db, set it to NULL or ""
|
||||
const char *db = "notexist";
|
||||
uint16_t port = 0; // 0 means use the default port
|
||||
TAOS *taos = taos_connect(host, user, passwd, db, port);
|
||||
if (taos == NULL) {
|
||||
int errno = taos_errno(NULL);
|
||||
char *msg = taos_errstr(NULL);
|
||||
printf("%d, %s\n", errno, msg);
|
||||
} else {
|
||||
printf("connected\n");
|
||||
taos_close(taos);
|
||||
}
|
||||
taos_cleanup();
|
||||
}
|
|
@ -0,0 +1,51 @@
|
|||
// compile with
|
||||
// gcc -o insert_example insert_example.c -ltaos
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include "taos.h"
|
||||
|
||||
|
||||
/**
|
||||
* @brief execute sql and print affected rows.
|
||||
*
|
||||
* @param taos
|
||||
* @param sql
|
||||
*/
|
||||
void executeSQL(TAOS *taos, const char *sql) {
|
||||
TAOS_RES *res = taos_query(taos, sql);
|
||||
int code = taos_errno(res);
|
||||
if (code != 0) {
|
||||
printf("Error code: %d; Message: %s\n", code, taos_errstr(res));
|
||||
taos_free_result(res);
|
||||
taos_close(taos);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
int affectedRows = taos_affected_rows(res);
|
||||
printf("affected rows %d\n", affectedRows);
|
||||
taos_free_result(res);
|
||||
}
|
||||
|
||||
|
||||
|
||||
int main() {
|
||||
TAOS *taos = taos_connect("localhost", "root", "taosdata", NULL, 6030);
|
||||
if (taos == NULL) {
|
||||
printf("failed to connect to server\n");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
executeSQL(taos, "CREATE DATABASE power");
|
||||
executeSQL(taos, "USE power");
|
||||
executeSQL(taos, "CREATE STABLE meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)");
|
||||
executeSQL(taos, "INSERT INTO d1001 USING meters TAGS(Beijing.Chaoyang, 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)"
|
||||
"d1002 USING meters TAGS(Beijing.Chaoyang, 3) VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000)"
|
||||
"d1003 USING meters TAGS(Beijing.Haidian, 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)"
|
||||
"d1004 USING meters TAGS(Beijing.Haidian, 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)");
|
||||
taos_close(taos);
|
||||
taos_cleanup();
|
||||
}
|
||||
|
||||
// output:
|
||||
// affected rows 0
|
||||
// affected rows 0
|
||||
// affected rows 0
|
||||
// affected rows 8
|
|
@ -0,0 +1,52 @@
|
|||
// compile with
|
||||
// gcc -o json_protocol_example json_protocol_example.c -ltaos
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "taos.h"
|
||||
|
||||
void executeSQL(TAOS *taos, const char *sql) {
|
||||
TAOS_RES *res = taos_query(taos, sql);
|
||||
int code = taos_errno(res);
|
||||
if (code != 0) {
|
||||
printf("%s\n", taos_errstr(res));
|
||||
taos_free_result(res);
|
||||
taos_close(taos);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
taos_free_result(res);
|
||||
}
|
||||
|
||||
// ANCHOR: main
|
||||
int main() {
|
||||
TAOS *taos = taos_connect("localhost", "root", "taosdata", "", 6030);
|
||||
if (taos == NULL) {
|
||||
printf("failed to connect to server\n");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
executeSQL(taos, "DROP DATABASE IF EXISTS test");
|
||||
executeSQL(taos, "CREATE DATABASE test");
|
||||
executeSQL(taos, "USE test");
|
||||
char *line =
|
||||
"[{\"metric\": \"meters.current\", \"timestamp\": 1648432611249, \"value\": 10.3, \"tags\": {\"location\": "
|
||||
"\"Beijing.Chaoyang\", \"groupid\": 2}},{\"metric\": \"meters.voltage\", \"timestamp\": 1648432611249, "
|
||||
"\"value\": 219, \"tags\": {\"location\": \"Beijing.Haidian\", \"groupid\": 1}},{\"metric\": \"meters.current\", "
|
||||
"\"timestamp\": 1648432611250, \"value\": 12.6, \"tags\": {\"location\": \"Beijing.Chaoyang\", \"groupid\": "
|
||||
"2}},{\"metric\": \"meters.voltage\", \"timestamp\": 1648432611250, \"value\": 221, \"tags\": {\"location\": "
|
||||
"\"Beijing.Haidian\", \"groupid\": 1}}]";
|
||||
|
||||
char *lines[] = {line};
|
||||
TAOS_RES *res = taos_schemaless_insert(taos, lines, 1, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED);
|
||||
if (taos_errno(res) != 0) {
|
||||
printf("failed to insert schema-less data, reason: %s\n", taos_errstr(res));
|
||||
} else {
|
||||
int affectedRow = taos_affected_rows(res);
|
||||
printf("successfully inserted %d rows\n", affectedRow);
|
||||
}
|
||||
taos_free_result(res);
|
||||
taos_close(taos);
|
||||
taos_cleanup();
|
||||
}
|
||||
// output:
|
||||
// successfully inserted 4 rows
|
||||
// ANCHOR_END: main
|
|
@ -0,0 +1,47 @@
|
|||
// compile with
|
||||
// gcc -o line_example line_example.c -ltaos
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "taos.h"
|
||||
|
||||
void executeSQL(TAOS *taos, const char *sql) {
|
||||
TAOS_RES *res = taos_query(taos, sql);
|
||||
int code = taos_errno(res);
|
||||
if (code != 0) {
|
||||
printf("%s\n", taos_errstr(res));
|
||||
taos_free_result(res);
|
||||
taos_close(taos);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
taos_free_result(res);
|
||||
}
|
||||
|
||||
// ANCHOR: main
|
||||
int main() {
|
||||
TAOS *taos = taos_connect("localhost", "root", "taosdata", "", 0);
|
||||
if (taos == NULL) {
|
||||
printf("failed to connect to server\n");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
executeSQL(taos, "DROP DATABASE IF EXISTS test");
|
||||
executeSQL(taos, "CREATE DATABASE test");
|
||||
executeSQL(taos, "USE test");
|
||||
char *lines[] = {"meters,location=Beijing.Haidian,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249",
|
||||
"meters,location=Beijing.Haidian,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611250",
|
||||
"meters,location=Beijing.Haidian,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249",
|
||||
"meters,location=Beijing.Haidian,groupid=3 current=11.3,voltage=221,phase=0.35 1648432611250"};
|
||||
TAOS_RES *res = taos_schemaless_insert(taos, lines, 4, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_MILLI_SECONDS);
|
||||
if (taos_errno(res) != 0) {
|
||||
printf("failed to insert schema-less data, reason: %s\n", taos_errstr(res));
|
||||
} else {
|
||||
int affectedRows = taos_affected_rows(res);
|
||||
printf("successfully inserted %d rows\n", affectedRows);
|
||||
}
|
||||
taos_free_result(res);
|
||||
taos_close(taos);
|
||||
taos_cleanup();
|
||||
}
|
||||
// output:
|
||||
// successfully inserted 4 rows
|
||||
// ANCHOR_END: main
|
|
@ -0,0 +1,147 @@
|
|||
// compile with
|
||||
// gcc -o multi_bind_example multi_bind_example.c -ltaos
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "taos.h"
|
||||
|
||||
/**
|
||||
* @brief execute sql only and ignore result set
|
||||
*
|
||||
* @param taos
|
||||
* @param sql
|
||||
*/
|
||||
void executeSQL(TAOS *taos, const char *sql) {
|
||||
TAOS_RES *res = taos_query(taos, sql);
|
||||
int code = taos_errno(res);
|
||||
if (code != 0) {
|
||||
printf("%s\n", taos_errstr(res));
|
||||
taos_free_result(res);
|
||||
taos_close(taos);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
taos_free_result(res);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief exit program when error occur.
|
||||
*
|
||||
* @param stmt
|
||||
* @param code
|
||||
* @param msg
|
||||
*/
|
||||
void checkErrorCode(TAOS_STMT *stmt, int code, const char *msg) {
|
||||
if (code != 0) {
|
||||
printf("%s. error: %s\n", msg, taos_stmt_errstr(stmt));
|
||||
taos_stmt_close(stmt);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief insert data using stmt API
|
||||
*
|
||||
* @param taos
|
||||
*/
|
||||
void insertData(TAOS *taos) {
|
||||
// init
|
||||
TAOS_STMT *stmt = taos_stmt_init(taos);
|
||||
// prepare
|
||||
const char *sql = "INSERT INTO ? USING meters TAGS(?, ?) values(?, ?, ?, ?)";
|
||||
int code = taos_stmt_prepare(stmt, sql, 0);
|
||||
checkErrorCode(stmt, code, "failed to execute taos_stmt_prepare");
|
||||
// bind table name and tags
|
||||
TAOS_BIND tags[2];
|
||||
char *location = "Beijing.Chaoyang";
|
||||
int groupId = 2;
|
||||
tags[0].buffer_type = TSDB_DATA_TYPE_BINARY;
|
||||
tags[0].buffer_length = strlen(location);
|
||||
tags[0].length = &tags[0].buffer_length;
|
||||
tags[0].buffer = location;
|
||||
tags[0].is_null = NULL;
|
||||
|
||||
tags[1].buffer_type = TSDB_DATA_TYPE_INT;
|
||||
tags[1].buffer_length = sizeof(int);
|
||||
tags[1].length = &tags[1].buffer_length;
|
||||
tags[1].buffer = &groupId;
|
||||
tags[1].is_null = NULL;
|
||||
|
||||
code = taos_stmt_set_tbname_tags(stmt, "d1001", tags);
|
||||
checkErrorCode(stmt, code, "failed to execute taos_stmt_set_tbname_tags");
|
||||
|
||||
// highlight-start
|
||||
// insert two rows with multi binds
|
||||
TAOS_MULTI_BIND params[4];
|
||||
// values to bind
|
||||
int64_t ts[] = {1648432611249, 1648432611749};
|
||||
float current[] = {10.3, 12.6};
|
||||
int voltage[] = {219, 218};
|
||||
float phase[] = {0.31, 0.33};
|
||||
// is_null array
|
||||
char is_null[2] = {0};
|
||||
// length array
|
||||
int32_t int64Len[2] = {sizeof(int64_t)};
|
||||
int32_t floatLen[2] = {sizeof(float)};
|
||||
int32_t intLen[2] = {sizeof(int)};
|
||||
|
||||
params[0].buffer_type = TSDB_DATA_TYPE_TIMESTAMP;
|
||||
params[0].buffer_length = sizeof(int64_t);
|
||||
params[0].buffer = ts;
|
||||
params[0].length = int64Len;
|
||||
params[0].is_null = is_null;
|
||||
params[0].num = 2;
|
||||
|
||||
params[1].buffer_type = TSDB_DATA_TYPE_FLOAT;
|
||||
params[1].buffer_length = sizeof(float);
|
||||
params[1].buffer = current;
|
||||
params[1].length = floatLen;
|
||||
params[1].is_null = is_null;
|
||||
params[1].num = 2;
|
||||
|
||||
params[2].buffer_type = TSDB_DATA_TYPE_INT;
|
||||
params[2].buffer_length = sizeof(int);
|
||||
params[2].buffer = voltage;
|
||||
params[2].length = intLen;
|
||||
params[2].is_null = is_null;
|
||||
params[2].num = 2;
|
||||
|
||||
params[3].buffer_type = TSDB_DATA_TYPE_FLOAT;
|
||||
params[3].buffer_length = sizeof(float);
|
||||
params[3].buffer = phase;
|
||||
params[3].length = floatLen;
|
||||
params[3].is_null = is_null;
|
||||
params[3].num = 2;
|
||||
|
||||
code = taos_stmt_bind_param_batch(stmt, params); // bind batch
|
||||
checkErrorCode(stmt, code, "failed to execute taos_stmt_bind_param_batch");
|
||||
code = taos_stmt_add_batch(stmt); // add batch
|
||||
checkErrorCode(stmt, code, "failed to execute taos_stmt_add_batch");
|
||||
// highlight-end
|
||||
// execute
|
||||
code = taos_stmt_execute(stmt);
|
||||
checkErrorCode(stmt, code, "failed to execute taos_stmt_execute");
|
||||
int affectedRows = taos_stmt_affected_rows(stmt);
|
||||
printf("successfully inserted %d rows\n", affectedRows);
|
||||
// close
|
||||
taos_stmt_close(stmt);
|
||||
}
|
||||
|
||||
int main() {
|
||||
TAOS *taos = taos_connect("localhost", "root", "taosdata", NULL, 6030);
|
||||
if (taos == NULL) {
|
||||
printf("failed to connect to server\n");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
executeSQL(taos, "DROP DATABASE IF EXISTS power");
|
||||
executeSQL(taos, "CREATE DATABASE power");
|
||||
executeSQL(taos, "USE power");
|
||||
executeSQL(taos,
|
||||
"CREATE STABLE meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), "
|
||||
"groupId INT)");
|
||||
insertData(taos);
|
||||
taos_close(taos);
|
||||
taos_cleanup();
|
||||
}
|
||||
|
||||
// output:
|
||||
// successfully inserted 2 rows
|
|
@ -0,0 +1,143 @@
|
|||
// compile with:
|
||||
// gcc -o query_example query_example.c -ltaos
|
||||
#include <inttypes.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <taos.h>
|
||||
|
||||
typedef int16_t VarDataLenT;
|
||||
|
||||
#define TSDB_NCHAR_SIZE sizeof(int32_t)
|
||||
#define VARSTR_HEADER_SIZE sizeof(VarDataLenT)
|
||||
|
||||
#define GET_FLOAT_VAL(x) (*(float *)(x))
|
||||
#define GET_DOUBLE_VAL(x) (*(double *)(x))
|
||||
|
||||
#define varDataLen(v) ((VarDataLenT *)(v))[0]
|
||||
|
||||
int printRow(char *str, TAOS_ROW row, TAOS_FIELD *fields, int numFields) {
|
||||
int len = 0;
|
||||
char split = ' ';
|
||||
|
||||
for (int i = 0; i < numFields; ++i) {
|
||||
if (i > 0) {
|
||||
str[len++] = split;
|
||||
}
|
||||
|
||||
if (row[i] == NULL) {
|
||||
len += sprintf(str + len, "%s", "NULL");
|
||||
continue;
|
||||
}
|
||||
|
||||
switch (fields[i].type) {
|
||||
case TSDB_DATA_TYPE_TINYINT:
|
||||
len += sprintf(str + len, "%d", *((int8_t *)row[i]));
|
||||
break;
|
||||
|
||||
case TSDB_DATA_TYPE_UTINYINT:
|
||||
len += sprintf(str + len, "%u", *((uint8_t *)row[i]));
|
||||
break;
|
||||
|
||||
case TSDB_DATA_TYPE_SMALLINT:
|
||||
len += sprintf(str + len, "%d", *((int16_t *)row[i]));
|
||||
break;
|
||||
|
||||
case TSDB_DATA_TYPE_USMALLINT:
|
||||
len += sprintf(str + len, "%u", *((uint16_t *)row[i]));
|
||||
break;
|
||||
|
||||
case TSDB_DATA_TYPE_INT:
|
||||
len += sprintf(str + len, "%d", *((int32_t *)row[i]));
|
||||
break;
|
||||
|
||||
case TSDB_DATA_TYPE_UINT:
|
||||
len += sprintf(str + len, "%u", *((uint32_t *)row[i]));
|
||||
break;
|
||||
|
||||
case TSDB_DATA_TYPE_BIGINT:
|
||||
len += sprintf(str + len, "%" PRId64, *((int64_t *)row[i]));
|
||||
break;
|
||||
|
||||
case TSDB_DATA_TYPE_UBIGINT:
|
||||
len += sprintf(str + len, "%" PRIu64, *((uint64_t *)row[i]));
|
||||
break;
|
||||
|
||||
case TSDB_DATA_TYPE_FLOAT: {
|
||||
float fv = 0;
|
||||
fv = GET_FLOAT_VAL(row[i]);
|
||||
len += sprintf(str + len, "%f", fv);
|
||||
} break;
|
||||
|
||||
case TSDB_DATA_TYPE_DOUBLE: {
|
||||
double dv = 0;
|
||||
dv = GET_DOUBLE_VAL(row[i]);
|
||||
len += sprintf(str + len, "%lf", dv);
|
||||
} break;
|
||||
|
||||
case TSDB_DATA_TYPE_BINARY:
|
||||
case TSDB_DATA_TYPE_NCHAR: {
|
||||
int32_t charLen = varDataLen((char *)row[i] - VARSTR_HEADER_SIZE);
|
||||
memcpy(str + len, row[i], charLen);
|
||||
len += charLen;
|
||||
} break;
|
||||
|
||||
case TSDB_DATA_TYPE_TIMESTAMP:
|
||||
len += sprintf(str + len, "%" PRId64, *((int64_t *)row[i]));
|
||||
break;
|
||||
|
||||
case TSDB_DATA_TYPE_BOOL:
|
||||
len += sprintf(str + len, "%d", *((int8_t *)row[i]));
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return len;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief print column name and values of each row
|
||||
*
|
||||
* @param res
|
||||
* @return int
|
||||
*/
|
||||
static int printResult(TAOS_RES *res) {
|
||||
int numFields = taos_num_fields(res);
|
||||
TAOS_FIELD *fields = taos_fetch_fields(res);
|
||||
char header[256] = {0};
|
||||
int len = 0;
|
||||
for (int i = 0; i < numFields; ++i) {
|
||||
len += sprintf(header + len, "%s ", fields[i].name);
|
||||
}
|
||||
puts(header);
|
||||
|
||||
TAOS_ROW row = NULL;
|
||||
while ((row = taos_fetch_row(res))) {
|
||||
char temp[256] = {0};
|
||||
printRow(temp, row, fields, numFields);
|
||||
puts(temp);
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
TAOS *taos = taos_connect("localhost", "root", "taosdata", "power", 6030);
|
||||
if (taos == NULL) {
|
||||
puts("failed to connect to server");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
TAOS_RES *res = taos_query(taos, "SELECT * FROM meters LIMIT 2");
|
||||
if (taos_errno(res) != 0) {
|
||||
printf("failed to execute taos_query. error: %s\n", taos_errstr(res));
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
printResult(res);
|
||||
taos_free_result(res);
|
||||
taos_close(taos);
|
||||
taos_cleanup();
|
||||
}
|
||||
|
||||
// output:
|
||||
// ts current voltage phase location groupid
|
||||
// 1648432611249 10.300000 219 0.310000 Beijing.Chaoyang 2
|
||||
// 1648432611749 12.600000 218 0.330000 Beijing.Chaoyang 2
|
|
@ -0,0 +1,141 @@
|
|||
// compile with
|
||||
// gcc -o stmt_example stmt_example.c -ltaos
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "taos.h"
|
||||
|
||||
/**
|
||||
* @brief execute sql only.
|
||||
*
|
||||
* @param taos
|
||||
* @param sql
|
||||
*/
|
||||
void executeSQL(TAOS *taos, const char *sql) {
|
||||
TAOS_RES *res = taos_query(taos, sql);
|
||||
int code = taos_errno(res);
|
||||
if (code != 0) {
|
||||
printf("%s\n", taos_errstr(res));
|
||||
taos_free_result(res);
|
||||
taos_close(taos);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
taos_free_result(res);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief check return status and exit program when error occur.
|
||||
*
|
||||
* @param stmt
|
||||
* @param code
|
||||
* @param msg
|
||||
*/
|
||||
void checkErrorCode(TAOS_STMT *stmt, int code, const char* msg) {
|
||||
if (code != 0) {
|
||||
printf("%s. error: %s\n", msg, taos_stmt_errstr(stmt));
|
||||
taos_stmt_close(stmt);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
}
|
||||
|
||||
typedef struct {
|
||||
int64_t ts;
|
||||
float current;
|
||||
int voltage;
|
||||
float phase;
|
||||
} Row;
|
||||
|
||||
/**
|
||||
* @brief insert data using stmt API
|
||||
*
|
||||
* @param taos
|
||||
*/
|
||||
void insertData(TAOS *taos) {
|
||||
// init
|
||||
TAOS_STMT *stmt = taos_stmt_init(taos);
|
||||
// prepare
|
||||
const char *sql = "INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)";
|
||||
int code = taos_stmt_prepare(stmt, sql, 0);
|
||||
checkErrorCode(stmt, code, "failed to execute taos_stmt_prepare");
|
||||
// bind table name and tags
|
||||
TAOS_BIND tags[2];
|
||||
char* location = "Beijing.Chaoyang";
|
||||
int groupId = 2;
|
||||
tags[0].buffer_type = TSDB_DATA_TYPE_BINARY;
|
||||
tags[0].buffer_length = strlen(location);
|
||||
tags[0].length = &tags[0].buffer_length;
|
||||
tags[0].buffer = location;
|
||||
tags[0].is_null = NULL;
|
||||
|
||||
tags[1].buffer_type = TSDB_DATA_TYPE_INT;
|
||||
tags[1].buffer_length = sizeof(int);
|
||||
tags[1].length = &tags[1].buffer_length;
|
||||
tags[1].buffer = &groupId;
|
||||
tags[1].is_null = NULL;
|
||||
|
||||
code = taos_stmt_set_tbname_tags(stmt, "d1001", tags);
|
||||
checkErrorCode(stmt, code, "failed to execute taos_stmt_set_tbname_tags");
|
||||
|
||||
// insert two rows
|
||||
Row rows[2] = {
|
||||
{1648432611249, 10.3, 219, 0.31},
|
||||
{1648432611749, 12.6, 218, 0.33},
|
||||
};
|
||||
|
||||
TAOS_BIND values[4];
|
||||
values[0].buffer_type = TSDB_DATA_TYPE_TIMESTAMP;
|
||||
values[0].buffer_length = sizeof(int64_t);
|
||||
values[0].length = &values[0].buffer_length;
|
||||
values[0].is_null = NULL;
|
||||
|
||||
values[1].buffer_type = TSDB_DATA_TYPE_FLOAT;
|
||||
values[1].buffer_length = sizeof(float);
|
||||
values[1].length = &values[1].buffer_length;
|
||||
values[1].is_null = NULL;
|
||||
|
||||
values[2].buffer_type = TSDB_DATA_TYPE_INT;
|
||||
values[2].buffer_length = sizeof(int);
|
||||
values[2].length = &values[2].buffer_length;
|
||||
values[2].is_null = NULL;
|
||||
|
||||
values[3].buffer_type = TSDB_DATA_TYPE_FLOAT;
|
||||
values[3].buffer_length = sizeof(float);
|
||||
values[3].length = &values[3].buffer_length;
|
||||
values[3].is_null = NULL;
|
||||
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
values[0].buffer = &rows[i].ts;
|
||||
values[1].buffer = &rows[i].current;
|
||||
values[2].buffer = &rows[i].voltage;
|
||||
values[3].buffer = &rows[i].phase;
|
||||
code = taos_stmt_bind_param(stmt, values); // bind param
|
||||
checkErrorCode(stmt, code, "failed to execute taos_stmt_bind_param");
|
||||
code = taos_stmt_add_batch(stmt); // add batch
|
||||
checkErrorCode(stmt, code, "failed to execute taos_stmt_add_batch");
|
||||
}
|
||||
// execute
|
||||
code = taos_stmt_execute(stmt);
|
||||
checkErrorCode(stmt, code, "failed to execute taos_stmt_execute");
|
||||
int affectedRows = taos_stmt_affected_rows(stmt);
|
||||
printf("successfully inserted %d rows\n", affectedRows);
|
||||
// close
|
||||
taos_stmt_close(stmt);
|
||||
}
|
||||
|
||||
int main() {
|
||||
TAOS *taos = taos_connect("localhost", "root", "taosdata", NULL, 6030);
|
||||
if (taos == NULL) {
|
||||
printf("failed to connect to server\n");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
executeSQL(taos, "CREATE DATABASE power");
|
||||
executeSQL(taos, "USE power");
|
||||
executeSQL(taos, "CREATE STABLE meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)");
|
||||
insertData(taos);
|
||||
taos_close(taos);
|
||||
taos_cleanup();
|
||||
}
|
||||
|
||||
|
||||
// output:
|
||||
// successfully inserted 2 rows
|
|
@ -0,0 +1,66 @@
|
|||
// A simple demo for asynchronous subscription.
|
||||
// compile with:
|
||||
// gcc -o subscribe_demo subscribe_demo.c -ltaos
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <taos.h>
|
||||
|
||||
int nTotalRows;
|
||||
|
||||
/**
|
||||
* @brief callback function of subscription.
|
||||
*
|
||||
* @param tsub
|
||||
* @param res
|
||||
* @param param. the additional parameter passed to taos_subscribe
|
||||
* @param code. error code
|
||||
*/
|
||||
void subscribe_callback(TAOS_SUB* tsub, TAOS_RES* res, void* param, int code) {
|
||||
if (code != 0) {
|
||||
printf("error: %d\n", code);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
TAOS_ROW row = NULL;
|
||||
int num_fields = taos_num_fields(res);
|
||||
TAOS_FIELD* fields = taos_fetch_fields(res);
|
||||
int nRows = 0;
|
||||
|
||||
while ((row = taos_fetch_row(res))) {
|
||||
char buf[4096] = {0};
|
||||
taos_print_row(buf, row, fields, num_fields);
|
||||
puts(buf);
|
||||
nRows++;
|
||||
}
|
||||
|
||||
nTotalRows += nRows;
|
||||
printf("%d rows consumed.\n", nRows);
|
||||
}
|
||||
|
||||
int main() {
|
||||
TAOS* taos = taos_connect("localhost", "root", "taosdata", NULL, 6030);
|
||||
if (taos == NULL) {
|
||||
printf("failed to connect to server\n");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
int restart = 1; // if the topic already exists, where to subscribe from the begin.
|
||||
const char* topic = "topic-meter-current-bg-10";
|
||||
const char* sql = "select * from power.meters where current > 10";
|
||||
void* param = NULL; // additional parameter.
|
||||
int interval = 2000; // consumption interval in microseconds.
|
||||
TAOS_SUB* tsub = taos_subscribe(taos, restart, topic, sql, subscribe_callback, NULL, interval);
|
||||
|
||||
// wait for insert from others process. you can open TDengine CLI to insert some records for test.
|
||||
|
||||
getchar(); // press Enter to stop
|
||||
|
||||
printf("total rows consumed: %d\n", nTotalRows);
|
||||
int keep = 0; // whether to keep subscribe process
|
||||
taos_unsubscribe(tsub, keep);
|
||||
|
||||
taos_close(taos);
|
||||
taos_cleanup();
|
||||
}
|
|
@ -0,0 +1,54 @@
|
|||
// compile with
|
||||
// gcc -o telnet_line_example telnet_line_example.c -ltaos
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "taos.h"
|
||||
|
||||
void executeSQL(TAOS *taos, const char *sql) {
|
||||
TAOS_RES *res = taos_query(taos, sql);
|
||||
int code = taos_errno(res);
|
||||
if (code != 0) {
|
||||
printf("%s\n", taos_errstr(res));
|
||||
taos_free_result(res);
|
||||
taos_close(taos);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
taos_free_result(res);
|
||||
}
|
||||
|
||||
// ANCHOR: main
|
||||
int main() {
|
||||
TAOS *taos = taos_connect("localhost", "root", "taosdata", "", 6030);
|
||||
if (taos == NULL) {
|
||||
printf("failed to connect to server\n");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
executeSQL(taos, "DROP DATABASE IF EXISTS test");
|
||||
executeSQL(taos, "CREATE DATABASE test");
|
||||
executeSQL(taos, "USE test");
|
||||
char *lines[] = {
|
||||
"meters.current 1648432611249 10.3 location=Beijing.Chaoyang groupid=2",
|
||||
"meters.current 1648432611250 12.6 location=Beijing.Chaoyang groupid=2",
|
||||
"meters.current 1648432611249 10.8 location=Beijing.Haidian groupid=3",
|
||||
"meters.current 1648432611250 11.3 location=Beijing.Haidian groupid=3",
|
||||
"meters.voltage 1648432611249 219 location=Beijing.Chaoyang groupid=2",
|
||||
"meters.voltage 1648432611250 218 location=Beijing.Chaoyang groupid=2",
|
||||
"meters.voltage 1648432611249 221 location=Beijing.Haidian groupid=3",
|
||||
"meters.voltage 1648432611250 217 location=Beijing.Haidian groupid=3",
|
||||
};
|
||||
TAOS_RES *res = taos_schemaless_insert(taos, lines, 8, TSDB_SML_TELNET_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED);
|
||||
if (taos_errno(res) != 0) {
|
||||
printf("failed to insert schema-less data, reason: %s\n", taos_errstr(res));
|
||||
} else {
|
||||
int affectedRow = taos_affected_rows(res);
|
||||
printf("successfully inserted %d rows\n", affectedRow);
|
||||
}
|
||||
|
||||
taos_free_result(res);
|
||||
taos_close(taos);
|
||||
taos_cleanup();
|
||||
}
|
||||
// output:
|
||||
// successfully inserted 8 rows
|
||||
// ANCHOR_END: main
|
|
@ -0,0 +1,4 @@
|
|||
bin
|
||||
obj
|
||||
.vs
|
||||
*.sln
|
|
@ -0,0 +1,238 @@
|
|||
using TDengineDriver;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace TDengineExample
|
||||
{
|
||||
public class AsyncQueryExample
|
||||
{
|
||||
static void Main()
|
||||
{
|
||||
IntPtr conn = GetConnection();
|
||||
QueryAsyncCallback queryAsyncCallback = new QueryAsyncCallback(QueryCallback);
|
||||
TDengine.QueryAsync(conn, "select * from meters", queryAsyncCallback, IntPtr.Zero);
|
||||
Thread.Sleep(2000);
|
||||
TDengine.Close(conn);
|
||||
TDengine.Cleanup();
|
||||
}
|
||||
|
||||
static void QueryCallback(IntPtr param, IntPtr taosRes, int code)
|
||||
{
|
||||
if (code == 0 && taosRes != IntPtr.Zero)
|
||||
{
|
||||
FetchRowAsyncCallback fetchRowAsyncCallback = new FetchRowAsyncCallback(FetchRowCallback);
|
||||
TDengine.FetchRowAsync(taosRes, fetchRowAsyncCallback, param);
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"async query data failed, failed code {code}");
|
||||
}
|
||||
}
|
||||
|
||||
static void FetchRowCallback(IntPtr param, IntPtr taosRes, int numOfRows)
|
||||
{
|
||||
if (numOfRows > 0)
|
||||
{
|
||||
Console.WriteLine($"{numOfRows} rows async retrieved");
|
||||
DisplayRes(taosRes);
|
||||
TDengine.FetchRowAsync(taosRes, FetchRowCallback, param);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (numOfRows == 0)
|
||||
{
|
||||
Console.WriteLine("async retrieve complete.");
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"FetchRowAsync callback error, error code {numOfRows}");
|
||||
}
|
||||
TDengine.FreeResult(taosRes);
|
||||
}
|
||||
}
|
||||
|
||||
public static void DisplayRes(IntPtr res)
|
||||
{
|
||||
if (!IsValidResult(res))
|
||||
{
|
||||
TDengine.Cleanup();
|
||||
System.Environment.Exit(1);
|
||||
}
|
||||
|
||||
List<TDengineMeta> metaList = TDengine.FetchFields(res);
|
||||
int fieldCount = metaList.Count;
|
||||
// metaList.ForEach((item) => { Console.Write("{0} ({1}) \t|\t", item.name, item.size); });
|
||||
|
||||
List<object> dataList = QueryRes(res, metaList);
|
||||
for (int index = 0; index < dataList.Count; index++)
|
||||
{
|
||||
if (index % fieldCount == 0 && index != 0)
|
||||
{
|
||||
Console.WriteLine("");
|
||||
}
|
||||
Console.Write("{0} \t|\t", dataList[index].ToString());
|
||||
|
||||
}
|
||||
Console.WriteLine("");
|
||||
}
|
||||
|
||||
public static bool IsValidResult(IntPtr res)
|
||||
{
|
||||
if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0))
|
||||
{
|
||||
if (res != IntPtr.Zero)
|
||||
{
|
||||
Console.Write("reason: " + TDengine.Error(res));
|
||||
return false;
|
||||
}
|
||||
Console.WriteLine("");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static List<object> QueryRes(IntPtr res, List<TDengineMeta> meta)
|
||||
{
|
||||
IntPtr taosRow;
|
||||
List<object> dataRaw = new();
|
||||
while ((taosRow = TDengine.FetchRows(res)) != IntPtr.Zero)
|
||||
{
|
||||
dataRaw.AddRange(FetchRow(taosRow, res));
|
||||
}
|
||||
if (TDengine.ErrorNo(res) != 0)
|
||||
{
|
||||
Console.Write("Query is not complete, Error {0} {1}", TDengine.ErrorNo(res), TDengine.Error(res));
|
||||
}
|
||||
TDengine.FreeResult(res);
|
||||
Console.WriteLine("");
|
||||
return dataRaw;
|
||||
}
|
||||
|
||||
public static List<object> FetchRow(IntPtr taosRow, IntPtr taosRes)//, List<TDengineMeta> metaList, int numOfFiled
|
||||
{
|
||||
List<TDengineMeta> metaList = TDengine.FetchFields(taosRes);
|
||||
int numOfFiled = TDengine.FieldCount(taosRes);
|
||||
|
||||
|
||||
List<object> dataRaw = new();
|
||||
|
||||
IntPtr colLengthPrt = TDengine.FetchLengths(taosRes);
|
||||
int[] colLengthArr = new int[numOfFiled];
|
||||
Marshal.Copy(colLengthPrt, colLengthArr, 0, numOfFiled);
|
||||
|
||||
for (int i = 0; i < numOfFiled; i++)
|
||||
{
|
||||
TDengineMeta meta = metaList[i];
|
||||
IntPtr data = Marshal.ReadIntPtr(taosRow, IntPtr.Size * i);
|
||||
|
||||
if (data == IntPtr.Zero)
|
||||
{
|
||||
dataRaw.Add("NULL");
|
||||
continue;
|
||||
}
|
||||
switch ((TDengineDataType)meta.type)
|
||||
{
|
||||
case TDengineDataType.TSDB_DATA_TYPE_BOOL:
|
||||
bool v1 = Marshal.ReadByte(data) != 0;
|
||||
dataRaw.Add(v1);
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_TINYINT:
|
||||
sbyte v2 = (sbyte)Marshal.ReadByte(data);
|
||||
dataRaw.Add(v2);
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_SMALLINT:
|
||||
short v3 = Marshal.ReadInt16(data);
|
||||
dataRaw.Add(v3);
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_INT:
|
||||
int v4 = Marshal.ReadInt32(data);
|
||||
dataRaw.Add(v4);
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_BIGINT:
|
||||
long v5 = Marshal.ReadInt64(data);
|
||||
dataRaw.Add(v5);
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_FLOAT:
|
||||
float v6 = (float)Marshal.PtrToStructure(data, typeof(float));
|
||||
dataRaw.Add(v6);
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_DOUBLE:
|
||||
double v7 = (double)Marshal.PtrToStructure(data, typeof(double));
|
||||
dataRaw.Add(v7);
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_BINARY:
|
||||
string v8 = Marshal.PtrToStringUTF8(data, colLengthArr[i]);
|
||||
dataRaw.Add(v8);
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_TIMESTAMP:
|
||||
long v9 = Marshal.ReadInt64(data);
|
||||
dataRaw.Add(v9);
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_NCHAR:
|
||||
string v10 = Marshal.PtrToStringUTF8(data, colLengthArr[i]);
|
||||
dataRaw.Add(v10);
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_UTINYINT:
|
||||
byte v12 = Marshal.ReadByte(data);
|
||||
dataRaw.Add(v12.ToString());
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_USMALLINT:
|
||||
ushort v13 = (ushort)Marshal.ReadInt16(data);
|
||||
dataRaw.Add(v13);
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_UINT:
|
||||
uint v14 = (uint)Marshal.ReadInt32(data);
|
||||
dataRaw.Add(v14);
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_UBIGINT:
|
||||
ulong v15 = (ulong)Marshal.ReadInt64(data);
|
||||
dataRaw.Add(v15);
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_JSONTAG:
|
||||
string v16 = Marshal.PtrToStringUTF8(data, colLengthArr[i]);
|
||||
dataRaw.Add(v16);
|
||||
break;
|
||||
default:
|
||||
dataRaw.Add("nonsupport data type");
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
return dataRaw;
|
||||
}
|
||||
|
||||
static IntPtr GetConnection()
|
||||
{
|
||||
string host = "localhost";
|
||||
short port = 6030;
|
||||
string username = "root";
|
||||
string password = "taosdata";
|
||||
string dbname = "power";
|
||||
var conn = TDengine.Connect(host, username, password, dbname, port);
|
||||
if (conn == IntPtr.Zero)
|
||||
{
|
||||
Console.WriteLine("Connect to TDengine failed");
|
||||
Environment.Exit(0);
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("Connect to TDengine success");
|
||||
}
|
||||
return conn;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//output:
|
||||
//Connect to TDengine success
|
||||
//8 rows async retrieved
|
||||
|
||||
//1538548685000 | 10.3 | 219 | 0.31 | beijing.chaoyang | 2 |
|
||||
//1538548695000 | 12.6 | 218 | 0.33 | beijing.chaoyang | 2 |
|
||||
//1538548696800 | 12.3 | 221 | 0.31 | beijing.chaoyang | 2 |
|
||||
//1538548696650 | 10.3 | 218 | 0.25 | beijing.chaoyang | 3 |
|
||||
//1538548685500 | 11.8 | 221 | 0.28 | beijing.haidian | 2 |
|
||||
//1538548696600 | 13.4 | 223 | 0.29 | beijing.haidian | 2 |
|
||||
//1538548685000 | 10.8 | 223 | 0.29 | beijing.haidian | 3 |
|
||||
//1538548686500 | 11.5 | 221 | 0.35 | beijing.haidian | 3 |
|
||||
//async retrieve complete.
|
|
@ -0,0 +1,29 @@
|
|||
using TDengineDriver;
|
||||
|
||||
namespace TDengineExample
|
||||
{
|
||||
|
||||
internal class ConnectExample
|
||||
{
|
||||
static void Main(String[] args)
|
||||
{
|
||||
string host = "localhost";
|
||||
short port = 6030;
|
||||
string username = "root";
|
||||
string password = "taosdata";
|
||||
string dbname = "";
|
||||
|
||||
var conn = TDengine.Connect(host, username, password, dbname, port);
|
||||
if (conn == IntPtr.Zero)
|
||||
{
|
||||
Console.WriteLine("Connect to TDengine failed");
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("Connect to TDengine success");
|
||||
}
|
||||
TDengine.Close(conn);
|
||||
TDengine.Cleanup();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,77 @@
|
|||
using TDengineDriver;
|
||||
|
||||
namespace TDengineExample
|
||||
{
|
||||
internal class InfluxDBLineExample
|
||||
{
|
||||
static void Main()
|
||||
{
|
||||
IntPtr conn = GetConnection();
|
||||
PrepareDatabase(conn);
|
||||
string[] lines = {
|
||||
"meters,location=Beijing.Haidian,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249",
|
||||
"meters,location=Beijing.Haidian,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611250",
|
||||
"meters,location=Beijing.Haidian,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249",
|
||||
"meters,location=Beijing.Haidian,groupid=3 current=11.3,voltage=221,phase=0.35 1648432611250"
|
||||
};
|
||||
IntPtr res = TDengine.SchemalessInsert(conn, lines, lines.Length, (int)TDengineSchemalessProtocol.TSDB_SML_LINE_PROTOCOL, (int)TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_MILLI_SECONDS);
|
||||
if (TDengine.ErrorNo(res) != 0)
|
||||
{
|
||||
Console.WriteLine("SchemalessInsert failed since " + TDengine.Error(res));
|
||||
ExitProgram(conn, 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
int affectedRows = TDengine.AffectRows(res);
|
||||
Console.WriteLine($"SchemalessInsert success, affected {affectedRows} rows");
|
||||
}
|
||||
TDengine.FreeResult(res);
|
||||
ExitProgram(conn, 0);
|
||||
|
||||
}
|
||||
static IntPtr GetConnection()
|
||||
{
|
||||
string host = "localhost";
|
||||
short port = 6030;
|
||||
string username = "root";
|
||||
string password = "taosdata";
|
||||
string dbname = "";
|
||||
var conn = TDengine.Connect(host, username, password, dbname, port);
|
||||
if (conn == IntPtr.Zero)
|
||||
{
|
||||
Console.WriteLine("Connect to TDengine failed");
|
||||
TDengine.Cleanup();
|
||||
Environment.Exit(1);
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("Connect to TDengine success");
|
||||
}
|
||||
return conn;
|
||||
}
|
||||
|
||||
static void PrepareDatabase(IntPtr conn)
|
||||
{
|
||||
IntPtr res = TDengine.Query(conn, "CREATE DATABASE test");
|
||||
if (TDengine.ErrorNo(res) != 0)
|
||||
{
|
||||
Console.WriteLine("failed to create database, reason: " + TDengine.Error(res));
|
||||
ExitProgram(conn, 1);
|
||||
}
|
||||
res = TDengine.Query(conn, "USE test");
|
||||
if (TDengine.ErrorNo(res) != 0)
|
||||
{
|
||||
Console.WriteLine("failed to change database, reason: " + TDengine.Error(res));
|
||||
ExitProgram(conn, 1);
|
||||
}
|
||||
}
|
||||
|
||||
static void ExitProgram(IntPtr conn, int exitCode)
|
||||
{
|
||||
TDengine.Close(conn);
|
||||
TDengine.Cleanup();
|
||||
Environment.Exit(exitCode);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,76 @@
|
|||
using TDengineDriver;
|
||||
|
||||
namespace TDengineExample
|
||||
{
|
||||
internal class OptsJsonExample
|
||||
{
|
||||
static void Main()
|
||||
{
|
||||
IntPtr conn = GetConnection();
|
||||
PrepareDatabase(conn);
|
||||
string[] lines = { "[{\"metric\": \"meters.current\", \"timestamp\": 1648432611249, \"value\": 10.3, \"tags\": {\"location\": \"Beijing.Chaoyang\", \"groupid\": 2}}," +
|
||||
" {\"metric\": \"meters.voltage\", \"timestamp\": 1648432611249, \"value\": 219, \"tags\": {\"location\": \"Beijing.Haidian\", \"groupid\": 1}}, " +
|
||||
"{\"metric\": \"meters.current\", \"timestamp\": 1648432611250, \"value\": 12.6, \"tags\": {\"location\": \"Beijing.Chaoyang\", \"groupid\": 2}}," +
|
||||
" {\"metric\": \"meters.voltage\", \"timestamp\": 1648432611250, \"value\": 221, \"tags\": {\"location\": \"Beijing.Haidian\", \"groupid\": 1}}]"
|
||||
};
|
||||
|
||||
IntPtr res = TDengine.SchemalessInsert(conn, lines, 1, (int)TDengineSchemalessProtocol.TSDB_SML_JSON_PROTOCOL, (int)TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_NOT_CONFIGURED);
|
||||
if (TDengine.ErrorNo(res) != 0)
|
||||
{
|
||||
Console.WriteLine("SchemalessInsert failed since " + TDengine.Error(res));
|
||||
ExitProgram(conn, 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
int affectedRows = TDengine.AffectRows(res);
|
||||
Console.WriteLine($"SchemalessInsert success, affected {affectedRows} rows");
|
||||
}
|
||||
TDengine.FreeResult(res);
|
||||
ExitProgram(conn, 0);
|
||||
|
||||
}
|
||||
static IntPtr GetConnection()
|
||||
{
|
||||
string host = "localhost";
|
||||
short port = 6030;
|
||||
string username = "root";
|
||||
string password = "taosdata";
|
||||
string dbname = "";
|
||||
var conn = TDengine.Connect(host, username, password, dbname, port);
|
||||
if (conn == IntPtr.Zero)
|
||||
{
|
||||
Console.WriteLine("Connect to TDengine failed");
|
||||
TDengine.Cleanup();
|
||||
Environment.Exit(1);
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("Connect to TDengine success");
|
||||
}
|
||||
return conn;
|
||||
}
|
||||
|
||||
static void PrepareDatabase(IntPtr conn)
|
||||
{
|
||||
IntPtr res = TDengine.Query(conn, "CREATE DATABASE test");
|
||||
if (TDengine.ErrorNo(res) != 0)
|
||||
{
|
||||
Console.WriteLine("failed to create database, reason: " + TDengine.Error(res));
|
||||
ExitProgram(conn, 1);
|
||||
}
|
||||
res = TDengine.Query(conn, "USE test");
|
||||
if (TDengine.ErrorNo(res) != 0)
|
||||
{
|
||||
Console.WriteLine("failed to change database, reason: " + TDengine.Error(res));
|
||||
ExitProgram(conn, 1);
|
||||
}
|
||||
}
|
||||
|
||||
static void ExitProgram(IntPtr conn, int exitCode)
|
||||
{
|
||||
TDengine.Close(conn);
|
||||
TDengine.Cleanup();
|
||||
Environment.Exit(exitCode);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,80 @@
|
|||
using TDengineDriver;
|
||||
|
||||
namespace TDengineExample
|
||||
{
|
||||
internal class OptsTelnetExample
|
||||
{
|
||||
static void Main()
|
||||
{
|
||||
IntPtr conn = GetConnection();
|
||||
PrepareDatabase(conn);
|
||||
string[] lines = {
|
||||
"meters.current 1648432611249 10.3 location=Beijing.Chaoyang groupid=2",
|
||||
"meters.current 1648432611250 12.6 location=Beijing.Chaoyang groupid=2",
|
||||
"meters.current 1648432611249 10.8 location=Beijing.Haidian groupid=3",
|
||||
"meters.current 1648432611250 11.3 location=Beijing.Haidian groupid=3",
|
||||
"meters.voltage 1648432611249 219 location=Beijing.Chaoyang groupid=2",
|
||||
"meters.voltage 1648432611250 218 location=Beijing.Chaoyang groupid=2",
|
||||
"meters.voltage 1648432611249 221 location=Beijing.Haidian groupid=3",
|
||||
"meters.voltage 1648432611250 217 location=Beijing.Haidian groupid=3",
|
||||
};
|
||||
IntPtr res = TDengine.SchemalessInsert(conn, lines, lines.Length, (int)TDengineSchemalessProtocol.TSDB_SML_TELNET_PROTOCOL, (int)TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_NOT_CONFIGURED);
|
||||
if (TDengine.ErrorNo(res) != 0)
|
||||
{
|
||||
Console.WriteLine("SchemalessInsert failed since " + TDengine.Error(res));
|
||||
ExitProgram(conn, 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
int affectedRows = TDengine.AffectRows(res);
|
||||
Console.WriteLine($"SchemalessInsert success, affected {affectedRows} rows");
|
||||
}
|
||||
TDengine.FreeResult(res);
|
||||
ExitProgram(conn, 0);
|
||||
|
||||
}
|
||||
static IntPtr GetConnection()
|
||||
{
|
||||
string host = "localhost";
|
||||
short port = 6030;
|
||||
string username = "root";
|
||||
string password = "taosdata";
|
||||
string dbname = "";
|
||||
var conn = TDengine.Connect(host, username, password, dbname, port);
|
||||
if (conn == IntPtr.Zero)
|
||||
{
|
||||
Console.WriteLine("Connect to TDengine failed");
|
||||
TDengine.Cleanup();
|
||||
Environment.Exit(1);
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("Connect to TDengine success");
|
||||
}
|
||||
return conn;
|
||||
}
|
||||
|
||||
static void PrepareDatabase(IntPtr conn)
|
||||
{
|
||||
IntPtr res = TDengine.Query(conn, "CREATE DATABASE test");
|
||||
if (TDengine.ErrorNo(res) != 0)
|
||||
{
|
||||
Console.WriteLine("failed to create database, reason: " + TDengine.Error(res));
|
||||
ExitProgram(conn, 1);
|
||||
}
|
||||
res = TDengine.Query(conn, "USE test");
|
||||
if (TDengine.ErrorNo(res) != 0)
|
||||
{
|
||||
Console.WriteLine("failed to change database, reason: " + TDengine.Error(res));
|
||||
ExitProgram(conn, 1);
|
||||
}
|
||||
}
|
||||
|
||||
static void ExitProgram(IntPtr conn, int exitCode)
|
||||
{
|
||||
TDengine.Close(conn);
|
||||
TDengine.Cleanup();
|
||||
Environment.Exit(exitCode);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,162 @@
|
|||
using TDengineDriver;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace TDengineExample
|
||||
{
|
||||
internal class QueryExample
|
||||
{
|
||||
static void Main()
|
||||
{
|
||||
IntPtr conn = GetConnection();
|
||||
// run query
|
||||
IntPtr res = TDengine.Query(conn, "SELECT * FROM test.meters LIMIT 2");
|
||||
if (TDengine.ErrorNo(res) != 0)
|
||||
{
|
||||
Console.WriteLine("Failed to query since: " + TDengine.Error(res));
|
||||
TDengine.Close(conn);
|
||||
TDengine.Cleanup();
|
||||
return;
|
||||
}
|
||||
|
||||
// get filed count
|
||||
int fieldCount = TDengine.FieldCount(res);
|
||||
Console.WriteLine("fieldCount=" + fieldCount);
|
||||
|
||||
// print column names
|
||||
List<TDengineMeta> metas = TDengine.FetchFields(res);
|
||||
for (int i = 0; i < metas.Count; i++)
|
||||
{
|
||||
Console.Write(metas[i].name + "\t");
|
||||
}
|
||||
Console.WriteLine();
|
||||
|
||||
// print values
|
||||
IntPtr row;
|
||||
while ((row = TDengine.FetchRows(res)) != IntPtr.Zero)
|
||||
{
|
||||
List<TDengineMeta> metaList = TDengine.FetchFields(res);
|
||||
int numOfFiled = TDengine.FieldCount(res);
|
||||
|
||||
List<String> dataRaw = new List<string>();
|
||||
|
||||
IntPtr colLengthPrt = TDengine.FetchLengths(res);
|
||||
int[] colLengthArr = new int[numOfFiled];
|
||||
Marshal.Copy(colLengthPrt, colLengthArr, 0, numOfFiled);
|
||||
|
||||
for (int i = 0; i < numOfFiled; i++)
|
||||
{
|
||||
TDengineMeta meta = metaList[i];
|
||||
IntPtr data = Marshal.ReadIntPtr(row, IntPtr.Size * i);
|
||||
|
||||
if (data == IntPtr.Zero)
|
||||
{
|
||||
Console.Write("NULL\t");
|
||||
continue;
|
||||
}
|
||||
switch ((TDengineDataType)meta.type)
|
||||
{
|
||||
case TDengineDataType.TSDB_DATA_TYPE_BOOL:
|
||||
bool v1 = Marshal.ReadByte(data) == 0 ? false : true;
|
||||
Console.Write(v1.ToString() + "\t");
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_TINYINT:
|
||||
sbyte v2 = (sbyte)Marshal.ReadByte(data);
|
||||
Console.Write(v2.ToString() + "\t");
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_SMALLINT:
|
||||
short v3 = Marshal.ReadInt16(data);
|
||||
Console.Write(v3.ToString() + "\t");
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_INT:
|
||||
int v4 = Marshal.ReadInt32(data);
|
||||
Console.Write(v4.ToString() + "\t");
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_BIGINT:
|
||||
long v5 = Marshal.ReadInt64(data);
|
||||
Console.Write(v5.ToString() + "\t");
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_FLOAT:
|
||||
float v6 = (float)Marshal.PtrToStructure(data, typeof(float));
|
||||
Console.Write(v6.ToString() + "\t");
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_DOUBLE:
|
||||
double v7 = (double)Marshal.PtrToStructure(data, typeof(double));
|
||||
Console.Write(v7.ToString() + "\t");
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_BINARY:
|
||||
string v8 = Marshal.PtrToStringUTF8(data, colLengthArr[i]);
|
||||
Console.Write(v8 + "\t");
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_TIMESTAMP:
|
||||
long v9 = Marshal.ReadInt64(data);
|
||||
Console.Write(v9.ToString() + "\t");
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_NCHAR:
|
||||
string v10 = Marshal.PtrToStringUTF8(data, colLengthArr[i]);
|
||||
Console.Write(v10 + "\t");
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_UTINYINT:
|
||||
byte v12 = Marshal.ReadByte(data);
|
||||
Console.Write(v12.ToString() + "\t");
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_USMALLINT:
|
||||
ushort v13 = (ushort)Marshal.ReadInt16(data);
|
||||
Console.Write(v13.ToString() + "\t");
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_UINT:
|
||||
uint v14 = (uint)Marshal.ReadInt32(data);
|
||||
Console.Write(v14.ToString() + "\t");
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_UBIGINT:
|
||||
ulong v15 = (ulong)Marshal.ReadInt64(data);
|
||||
Console.Write(v15.ToString() + "\t");
|
||||
break;
|
||||
case TDengineDataType.TSDB_DATA_TYPE_JSONTAG:
|
||||
string v16 = Marshal.PtrToStringUTF8(data, colLengthArr[i]);
|
||||
Console.Write(v16 + "\t");
|
||||
break;
|
||||
default:
|
||||
Console.Write("nonsupport data type value");
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
Console.WriteLine();
|
||||
}
|
||||
if (TDengine.ErrorNo(res) != 0)
|
||||
{
|
||||
Console.WriteLine($"Query is not complete, Error {TDengine.ErrorNo(res)} {TDengine.Error(res)}");
|
||||
}
|
||||
// exit
|
||||
TDengine.FreeResult(res);
|
||||
TDengine.Close(conn);
|
||||
TDengine.Cleanup();
|
||||
}
|
||||
static IntPtr GetConnection()
|
||||
{
|
||||
string host = "localhost";
|
||||
short port = 6030;
|
||||
string username = "root";
|
||||
string password = "taosdata";
|
||||
string dbname = "power";
|
||||
var conn = TDengine.Connect(host, username, password, dbname, port);
|
||||
if (conn == IntPtr.Zero)
|
||||
{
|
||||
Console.WriteLine("Connect to TDengine failed");
|
||||
System.Environment.Exit(0);
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("Connect to TDengine success");
|
||||
}
|
||||
return conn;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// output:
|
||||
// Connect to TDengine success
|
||||
// fieldCount=6
|
||||
// ts current voltage phase location groupid
|
||||
// 1648432611249 10.3 219 0.31 Beijing.Chaoyang 2
|
||||
// 1648432611749 12.6 218 0.33 Beijing.Chaoyang 2
|
|
@ -0,0 +1,69 @@
|
|||
using TDengineDriver;
|
||||
|
||||
|
||||
namespace TDengineExample
|
||||
{
|
||||
internal class SQLInsertExample
|
||||
{
|
||||
|
||||
static void Main()
|
||||
{
|
||||
IntPtr conn = GetConnection();
|
||||
IntPtr res = TDengine.Query(conn, "CREATE DATABASE power");
|
||||
CheckRes(conn, res, "failed to create database");
|
||||
res = TDengine.Query(conn, "USE power");
|
||||
CheckRes(conn, res, "failed to change database");
|
||||
res = TDengine.Query(conn, "CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)");
|
||||
CheckRes(conn, res, "failed to create stable");
|
||||
var sql = "INSERT INTO d1001 USING meters TAGS(Beijing.Chaoyang, 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) " +
|
||||
"d1002 USING power.meters TAGS(Beijing.Chaoyang, 3) VALUES('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000) " +
|
||||
"d1003 USING power.meters TAGS(Beijing.Haidian, 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) " +
|
||||
"d1004 USING power.meters TAGS(Beijing.Haidian, 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)";
|
||||
res = TDengine.Query(conn, sql);
|
||||
CheckRes(conn, res, "failed to insert data");
|
||||
int affectedRows = TDengine.AffectRows(res);
|
||||
Console.WriteLine("affectedRows " + affectedRows);
|
||||
ExitProgram(conn, 0);
|
||||
}
|
||||
|
||||
static IntPtr GetConnection()
|
||||
{
|
||||
string host = "localhost";
|
||||
short port = 6030;
|
||||
string username = "root";
|
||||
string password = "taosdata";
|
||||
string dbname = "";
|
||||
var conn = TDengine.Connect(host, username, password, dbname, port);
|
||||
if (conn == IntPtr.Zero)
|
||||
{
|
||||
Console.WriteLine("Connect to TDengine failed");
|
||||
Environment.Exit(0);
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("Connect to TDengine success");
|
||||
}
|
||||
return conn;
|
||||
}
|
||||
|
||||
static void CheckRes(IntPtr conn, IntPtr res, String errorMsg)
|
||||
{
|
||||
if (TDengine.ErrorNo(res) != 0)
|
||||
{
|
||||
Console.Write(errorMsg + " since: " + TDengine.Error(res));
|
||||
ExitProgram(conn, 1);
|
||||
}
|
||||
}
|
||||
|
||||
static void ExitProgram(IntPtr conn, int exitCode)
|
||||
{
|
||||
TDengine.Close(conn);
|
||||
TDengine.Cleanup();
|
||||
Environment.Exit(exitCode);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// output:
|
||||
// Connect to TDengine success
|
||||
// affectedRows 8
|
|
@ -0,0 +1,115 @@
|
|||
using TDengineDriver;
|
||||
|
||||
namespace TDengineExample
|
||||
{
|
||||
internal class StmtInsertExample
|
||||
{
|
||||
private static IntPtr conn;
|
||||
private static IntPtr stmt;
|
||||
static void Main()
|
||||
{
|
||||
conn = GetConnection();
|
||||
PrepareSTable();
|
||||
// 1. init and prepare
|
||||
stmt = TDengine.StmtInit(conn);
|
||||
if (stmt == IntPtr.Zero)
|
||||
{
|
||||
Console.WriteLine("failed to init stmt, " + TDengine.Error(stmt));
|
||||
ExitProgram();
|
||||
}
|
||||
int res = TDengine.StmtPrepare(stmt, "INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)");
|
||||
CheckStmtRes(res, "failed to prepare stmt");
|
||||
|
||||
// 2. bind table name and tags
|
||||
TAOS_BIND[] tags = new TAOS_BIND[2] { TaosBind.BindBinary("Beijing.Chaoyang"), TaosBind.BindInt(2) };
|
||||
res = TDengine.StmtSetTbnameTags(stmt, "d1001", tags);
|
||||
CheckStmtRes(res, "failed to bind table name and tags");
|
||||
|
||||
// 3. bind values
|
||||
TAOS_MULTI_BIND[] values = new TAOS_MULTI_BIND[4] {
|
||||
TaosMultiBind.MultiBindTimestamp(new long[2] { 1648432611249, 1648432611749}),
|
||||
TaosMultiBind.MultiBindFloat(new float?[2] { 10.3f, 12.6f}),
|
||||
TaosMultiBind.MultiBindInt(new int?[2] { 219, 218}),
|
||||
TaosMultiBind.MultiBindFloat(new float?[2]{ 0.31f, 0.33f})
|
||||
};
|
||||
res = TDengine.StmtBindParamBatch(stmt, values);
|
||||
CheckStmtRes(res, "failed to bind params");
|
||||
|
||||
// 4. add batch
|
||||
res = TDengine.StmtAddBatch(stmt);
|
||||
CheckStmtRes(res, "failed to add batch");
|
||||
|
||||
// 5. execute
|
||||
res = TDengine.StmtExecute(stmt);
|
||||
CheckStmtRes(res, "faild to execute");
|
||||
|
||||
// 6. free
|
||||
TaosBind.FreeTaosBind(tags);
|
||||
TaosMultiBind.FreeTaosBind(values);
|
||||
TDengine.Close(conn);
|
||||
TDengine.Cleanup();
|
||||
}
|
||||
|
||||
static IntPtr GetConnection()
|
||||
{
|
||||
string host = "localhost";
|
||||
short port = 6030;
|
||||
string username = "root";
|
||||
string password = "taosdata";
|
||||
string dbname = "";
|
||||
var conn = TDengine.Connect(host, username, password, dbname, port);
|
||||
if (conn == IntPtr.Zero)
|
||||
{
|
||||
Console.WriteLine("Connect to TDengine failed");
|
||||
Environment.Exit(0);
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("Connect to TDengine success");
|
||||
}
|
||||
return conn;
|
||||
}
|
||||
|
||||
|
||||
|
||||
static void PrepareSTable()
|
||||
{
|
||||
IntPtr res = TDengine.Query(conn, "CREATE DATABASE power");
|
||||
CheckResPtr(res, "failed to create database");
|
||||
res = TDengine.Query(conn, "USE power");
|
||||
CheckResPtr(res, "failed to change database");
|
||||
res = TDengine.Query(conn, "CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)");
|
||||
CheckResPtr(res, "failed to create stable");
|
||||
}
|
||||
|
||||
static void CheckStmtRes(int res, string errorMsg)
|
||||
{
|
||||
if (res != 0)
|
||||
{
|
||||
Console.WriteLine(errorMsg + ", " + TDengine.StmtErrorStr(stmt));
|
||||
int code = TDengine.StmtClose(stmt);
|
||||
if (code != 0)
|
||||
{
|
||||
Console.WriteLine($"falied to close stmt, {code} reason: {TDengine.StmtErrorStr(stmt)} ");
|
||||
}
|
||||
ExitProgram();
|
||||
}
|
||||
}
|
||||
|
||||
static void CheckResPtr(IntPtr res, string errorMsg)
|
||||
{
|
||||
if (TDengine.ErrorNo(res) != 0)
|
||||
{
|
||||
Console.WriteLine(errorMsg + " since:" + TDengine.Error(res));
|
||||
ExitProgram();
|
||||
}
|
||||
}
|
||||
|
||||
static void ExitProgram()
|
||||
{
|
||||
TDengine.Close(conn);
|
||||
TDengine.Cleanup();
|
||||
Environment.Exit(1);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace csharp
|
||||
{
|
||||
internal class SubscribeDemo
|
||||
{
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<StartupObject>TDengineExample.AsyncQueryExample</StartupObject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="TDengine.Connector" Version="1.0.6" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
|
@ -0,0 +1,15 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<StartupObject>TDengineExample.ConnectExample</StartupObject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="TDengine.Connector" Version="1.0.6" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
|
@ -0,0 +1,15 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<StartupObject>TDengineExample.InfluxDBLineExample</StartupObject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="TDengine.Connector" Version="1.0.6" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
|
@ -0,0 +1,15 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<StartupObject>TDengineExample.OptsJsonExample</StartupObject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="TDengine.Connector" Version="1.0.6" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
|
@ -0,0 +1,15 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<StartupObject>TDengineExample.OptsTelnetExample</StartupObject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="TDengine.Connector" Version="1.0.6" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
|
@ -0,0 +1,15 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<StartupObject>TDengineExample.QueryExample</StartupObject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="TDengine.Connector" Version="1.0.6" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
|
@ -0,0 +1,15 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<StartupObject>TDengineExample.SQLInsertExample</StartupObject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="TDengine.Connector" Version="1.0.6" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
|
@ -0,0 +1,15 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<StartupObject>TDengineExample.StmtInsertExample</StartupObject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="TDengine.Connector" Version="1.0.6" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
|
@ -0,0 +1,15 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<StartupObject>TDengineExample.SubscribeDemo</StartupObject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="TDengine.Connector" Version="1.0.6" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
|
@ -0,0 +1,3 @@
|
|||
.idea
|
||||
.vscode
|
||||
tmp/
|
|
@ -0,0 +1,17 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/taosdata/driver-go/v2/af"
|
||||
)
|
||||
|
||||
func main() {
|
||||
conn, err := af.Open("localhost", "root", "taosdata", "", 6030)
|
||||
defer conn.Close()
|
||||
if err != nil {
|
||||
fmt.Println("failed to connect, err:", err)
|
||||
} else {
|
||||
fmt.Println("connected")
|
||||
}
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
_ "github.com/taosdata/driver-go/v2/taosSql"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var taosDSN = "root:taosdata@tcp(localhost:6030)/"
|
||||
taos, err := sql.Open("taosSql", taosDSN)
|
||||
if err != nil {
|
||||
fmt.Println("failed to connect TDengine, err:", err)
|
||||
return
|
||||
}
|
||||
fmt.Println("Connected")
|
||||
defer taos.Close()
|
||||
}
|
||||
|
||||
// use
|
||||
// var taosDSN = "root:taosdata@tcp(localhost:6030)/dbName"
|
||||
// if you want to connect to a default database.
|
|
@ -0,0 +1,23 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
_ "github.com/taosdata/driver-go/v2/taosRestful"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var taosDSN = "root:taosdata@http(localhost:6041)/"
|
||||
taos, err := sql.Open("taosRestful", taosDSN)
|
||||
if err != nil {
|
||||
fmt.Println("failed to connect TDengine, err:", err)
|
||||
return
|
||||
}
|
||||
fmt.Println("Connected")
|
||||
defer taos.Close()
|
||||
}
|
||||
|
||||
// use
|
||||
// var taosDSN = "root:taosdata@http(localhost:6041)/dbName"
|
||||
// if you want to connect to a default database.
|
|
@ -0,0 +1,17 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/taosdata/driver-go/v2/wrapper"
|
||||
)
|
||||
|
||||
func main() {
|
||||
conn, err := wrapper.TaosConnect("localhost", "root", "taosdata", "", 6030)
|
||||
defer wrapper.TaosClose(conn)
|
||||
if err != nil {
|
||||
fmt.Println("fail to connect, err:", err)
|
||||
} else {
|
||||
fmt.Println("connected")
|
||||
}
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
module goexample
|
||||
|
||||
go 1.17
|
||||
|
||||
require github.com/taosdata/driver-go/v2 develop
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/taosdata/driver-go/v2/af"
|
||||
)
|
||||
|
||||
func prepareDatabase(conn *af.Connector) {
|
||||
_, err := conn.Exec("CREATE DATABASE test")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
_, err = conn.Exec("USE test")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
conn, err := af.Open("localhost", "root", "taosdata", "", 6030)
|
||||
if err != nil {
|
||||
fmt.Println("fail to connect, err:", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
prepareDatabase(conn)
|
||||
|
||||
payload := `[{"metric": "meters.current", "timestamp": 1648432611249, "value": 10.3, "tags": {"location": "Beijing.Chaoyang", "groupid": 2}},
|
||||
{"metric": "meters.voltage", "timestamp": 1648432611249, "value": 219, "tags": {"location": "Beijing.Haidian", "groupid": 1}},
|
||||
{"metric": "meters.current", "timestamp": 1648432611250, "value": 12.6, "tags": {"location": "Beijing.Chaoyang", "groupid": 2}},
|
||||
{"metric": "meters.voltage", "timestamp": 1648432611250, "value": 221, "tags": {"location": "Beijing.Haidian", "groupid": 1}}]`
|
||||
|
||||
err = conn.OpenTSDBInsertJsonPayload(payload)
|
||||
if err != nil {
|
||||
fmt.Println("insert error:", err)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/taosdata/driver-go/v2/af"
|
||||
)
|
||||
|
||||
func prepareDatabase(conn *af.Connector) {
|
||||
_, err := conn.Exec("CREATE DATABASE test")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
_, err = conn.Exec("USE test")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
conn, err := af.Open("localhost", "root", "taosdata", "", 6030)
|
||||
if err != nil {
|
||||
fmt.Println("fail to connect, err:", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
prepareDatabase(conn)
|
||||
var lines = []string{
|
||||
"meters,location=Beijing.Haidian,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249",
|
||||
"meters,location=Beijing.Haidian,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611250",
|
||||
"meters,location=Beijing.Haidian,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249",
|
||||
"meters,location=Beijing.Haidian,groupid=3 current=11.3,voltage=221,phase=0.35 1648432611250",
|
||||
}
|
||||
|
||||
err = conn.InfluxDBInsertLines(lines, "ms")
|
||||
if err != nil {
|
||||
fmt.Println("insert error:", err)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
_ "github.com/taosdata/driver-go/v2/taosRestful"
|
||||
)
|
||||
|
||||
func createStable(taos *sql.DB) {
|
||||
_, err := taos.Exec("CREATE DATABASE power")
|
||||
if err != nil {
|
||||
fmt.Println("failed to create database, err:", err)
|
||||
}
|
||||
_, err = taos.Exec("CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)")
|
||||
if err != nil {
|
||||
fmt.Println("failed to create stable, err:", err)
|
||||
}
|
||||
}
|
||||
|
||||
func insertData(taos *sql.DB) {
|
||||
sql := `INSERT INTO power.d1001 USING power.meters TAGS(Beijing.Chaoyang, 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(Beijing.Chaoyang, 3) VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000)
|
||||
power.d1003 USING power.meters TAGS(Beijing.Haidian, 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(Beijing.Haidian, 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)`
|
||||
result, err := taos.Exec(sql)
|
||||
if err != nil {
|
||||
fmt.Println("failed to insert, err:", err)
|
||||
return
|
||||
}
|
||||
rowsAffected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
fmt.Println("failed to get affected rows, err:", err)
|
||||
return
|
||||
}
|
||||
fmt.Println("RowsAffected", rowsAffected)
|
||||
}
|
||||
|
||||
func main() {
|
||||
var taosDSN = "root:taosdata@http(localhost:6041)/"
|
||||
taos, err := sql.Open("taosRestful", taosDSN)
|
||||
if err != nil {
|
||||
fmt.Println("failed to connect TDengine, err:", err)
|
||||
return
|
||||
}
|
||||
defer taos.Close()
|
||||
createStable(taos)
|
||||
insertData(taos)
|
||||
}
|
|
@ -0,0 +1,73 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/taosdata/driver-go/v2/af"
|
||||
"github.com/taosdata/driver-go/v2/af/param"
|
||||
"github.com/taosdata/driver-go/v2/common"
|
||||
)
|
||||
|
||||
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
|
||||
tagParams := param.NewParam(2).AddBinary([]byte("Beijing.Chaoyang")).AddInt(2)
|
||||
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")
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/taosdata/driver-go/v2/af"
|
||||
)
|
||||
|
||||
func prepareDatabase(conn *af.Connector) {
|
||||
_, err := conn.Exec("CREATE DATABASE test")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
_, err = conn.Exec("USE test")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
conn, err := af.Open("localhost", "root", "taosdata", "", 6030)
|
||||
if err != nil {
|
||||
fmt.Println("fail to connect, err:", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
prepareDatabase(conn)
|
||||
var lines = []string{
|
||||
"meters.current 1648432611249 10.3 location=Beijing.Chaoyang groupid=2",
|
||||
"meters.current 1648432611250 12.6 location=Beijing.Chaoyang groupid=2",
|
||||
"meters.current 1648432611249 10.8 location=Beijing.Haidian groupid=3",
|
||||
"meters.current 1648432611250 11.3 location=Beijing.Haidian groupid=3",
|
||||
"meters.voltage 1648432611249 219 location=Beijing.Chaoyang groupid=2",
|
||||
"meters.voltage 1648432611250 218 location=Beijing.Chaoyang groupid=2",
|
||||
"meters.voltage 1648432611249 221 location=Beijing.Haidian groupid=3",
|
||||
"meters.voltage 1648432611250 217 location=Beijing.Haidian groupid=3",
|
||||
}
|
||||
|
||||
err = conn.OpenTSDBInsertTelnetLines(lines)
|
||||
if err != nil {
|
||||
fmt.Println("insert error:", err)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
fmt.Println("hello world!")
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
_ "github.com/taosdata/driver-go/v2/taosRestful"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var taosDSN = "root:taosdata@http(localhost:6041)/power"
|
||||
taos, err := sql.Open("taosRestful", taosDSN)
|
||||
if err != nil {
|
||||
fmt.Println("failed to connect TDengine, err:", err)
|
||||
return
|
||||
}
|
||||
defer taos.Close()
|
||||
rows, err := taos.Query("SELECT ts, current FROM meters LIMIT 2")
|
||||
if err != nil {
|
||||
fmt.Println("failed to select from table, err:", err)
|
||||
return
|
||||
}
|
||||
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var r struct {
|
||||
ts time.Time
|
||||
current float32
|
||||
}
|
||||
err := rows.Scan(&r.ts, &r.current)
|
||||
if err != nil {
|
||||
fmt.Println("scan error:\n", err)
|
||||
return
|
||||
}
|
||||
fmt.Println(r.ts, r.current)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Tags struct {
|
||||
Location string `json:"location"`
|
||||
Groupid int32 `json:"groupid"`
|
||||
}
|
||||
|
||||
type Metric struct {
|
||||
Metric string `json:"metric"`
|
||||
Timestamp int64 `json:"timestamp"`
|
||||
Value int32 `json:"value"`
|
||||
Tags Tags `json:"tags"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
client := http.Client{}
|
||||
for i := 0; i < 10; i++ {
|
||||
metric := Metric{"voltage", time.Now().UnixMilli(), 1, Tags{"A", 1}}
|
||||
json, err := json.Marshal(metric)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
req, err := http.NewRequest("POST", "http://localhost:6041/opentsdb/v1/put/json/rest_go", bytes.NewBuffer(json))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Basic cm9vdDp0YW9zZGF0YQ==")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Printf("%v\n", resp)
|
||||
time.Sleep(time.Second)
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,53 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
taos "github.com/taosdata/driver-go/v2/af"
|
||||
)
|
||||
|
||||
func main() {
|
||||
db, err := taos.Open("", "", "", "log", 0)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer db.Close()
|
||||
topic, err := db.Subscribe(false, "taoslogtail", "select ts, level, ipaddr, content from log", time.Second)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(2)
|
||||
}
|
||||
defer topic.Unsubscribe(true)
|
||||
for {
|
||||
func() {
|
||||
rows, err := topic.Consume()
|
||||
defer func() { rows.Close(); time.Sleep(time.Second) }()
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(3)
|
||||
}
|
||||
for {
|
||||
values := make([]driver.Value, 4)
|
||||
err := rows.Next(values)
|
||||
if err == io.EOF {
|
||||
break
|
||||
} else if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(4)
|
||||
}
|
||||
ts := values[0].(time.Time)
|
||||
level := values[1].(int8)
|
||||
ipaddr := values[2].(string)
|
||||
content := values[3].(string)
|
||||
fmt.Printf("%s %d %s %s\n", ts.Format(time.StampMilli), level, ipaddr, content)
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
// 未完成
|
|
@ -0,0 +1,2 @@
|
|||
.idea
|
||||
.vscode
|
|
@ -0,0 +1,35 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.taos</groupId>
|
||||
<artifactId>javaexample</artifactId>
|
||||
<version>1.0</version>
|
||||
|
||||
<name>JavaExample</name>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<!-- ANCHOR: dep-->
|
||||
<dependency>
|
||||
<groupId>com.taosdata.jdbc</groupId>
|
||||
<artifactId>taos-jdbcdriver</artifactId>
|
||||
<version>2.0.38</version>
|
||||
</dependency>
|
||||
<!-- ANCHOR_END: dep-->
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.13.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,25 @@
|
|||
package com.taos.example;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Properties;
|
||||
|
||||
import com.taosdata.jdbc.TSDBDriver;
|
||||
|
||||
public class JNIConnectExample {
|
||||
public static void main(String[] args) throws SQLException {
|
||||
String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata";
|
||||
Properties connProps = new Properties();
|
||||
connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
|
||||
connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
|
||||
connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
|
||||
Connection conn = DriverManager.getConnection(jdbcUrl, connProps);
|
||||
System.out.println("Connected");
|
||||
conn.close();
|
||||
}
|
||||
}
|
||||
|
||||
// use
|
||||
// String jdbcUrl = "jdbc:TAOS://localhost:6030/dbName?user=root&password=taosdata";
|
||||
// if you want to connect to a default database.
|
|
@ -0,0 +1,40 @@
|
|||
package com.taos.example;
|
||||
|
||||
import com.taosdata.jdbc.SchemalessWriter;
|
||||
import com.taosdata.jdbc.enums.SchemalessProtocolType;
|
||||
import com.taosdata.jdbc.enums.SchemalessTimestampType;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
public class JSONProtocolExample {
|
||||
private static Connection getConnection() throws SQLException {
|
||||
String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata";
|
||||
return DriverManager.getConnection(jdbcUrl);
|
||||
}
|
||||
|
||||
private static void createDatabase(Connection conn) throws SQLException {
|
||||
try (Statement stmt = conn.createStatement()) {
|
||||
stmt.execute("CREATE DATABASE IF NOT EXISTS test");
|
||||
stmt.execute("USE test");
|
||||
}
|
||||
}
|
||||
|
||||
private static String getJSONData() {
|
||||
return "[{\"metric\": \"meters.current\", \"timestamp\": 1648432611249, \"value\": 10.3, \"tags\": {\"location\": \"Beijing.Chaoyang\", \"groupid\": 2}}," +
|
||||
" {\"metric\": \"meters.voltage\", \"timestamp\": 1648432611249, \"value\": 219, \"tags\": {\"location\": \"Beijing.Haidian\", \"groupid\": 1}}, " +
|
||||
"{\"metric\": \"meters.current\", \"timestamp\": 1648432611250, \"value\": 12.6, \"tags\": {\"location\": \"Beijing.Chaoyang\", \"groupid\": 2}}," +
|
||||
" {\"metric\": \"meters.voltage\", \"timestamp\": 1648432611250, \"value\": 221, \"tags\": {\"location\": \"Beijing.Haidian\", \"groupid\": 1}}]";
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws SQLException {
|
||||
try (Connection conn = getConnection()) {
|
||||
createDatabase(conn);
|
||||
SchemalessWriter writer = new SchemalessWriter(conn);
|
||||
String jsonData = getJSONData();
|
||||
writer.write(jsonData, SchemalessProtocolType.JSON, SchemalessTimestampType.NOT_CONFIGURED);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package com.taos.example;
|
||||
|
||||
import com.taosdata.jdbc.SchemalessWriter;
|
||||
import com.taosdata.jdbc.enums.SchemalessProtocolType;
|
||||
import com.taosdata.jdbc.enums.SchemalessTimestampType;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
public class LineProtocolExample {
|
||||
// format: measurement,tag_set field_set timestamp
|
||||
private static String[] lines = {
|
||||
"meters,location=Beijing.Haidian,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249000", // micro
|
||||
// seconds
|
||||
"meters,location=Beijing.Haidian,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611249500",
|
||||
"meters,location=Beijing.Haidian,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249300",
|
||||
"meters,location=Beijing.Haidian,groupid=3 current=11.3,voltage=221,phase=0.35 1648432611249800",
|
||||
};
|
||||
|
||||
private static Connection getConnection() throws SQLException {
|
||||
String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata";
|
||||
return DriverManager.getConnection(jdbcUrl);
|
||||
}
|
||||
|
||||
private static void createDatabase(Connection conn) throws SQLException {
|
||||
try (Statement stmt = conn.createStatement()) {
|
||||
// the default precision is ms (microsecond), but we use us(microsecond) here.
|
||||
stmt.execute("CREATE DATABASE IF NOT EXISTS test PRECISION 'us'");
|
||||
stmt.execute("USE test");
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws SQLException {
|
||||
try (Connection conn = getConnection()) {
|
||||
createDatabase(conn);
|
||||
SchemalessWriter writer = new SchemalessWriter(conn);
|
||||
writer.write(lines, SchemalessProtocolType.LINE, SchemalessTimestampType.MICRO_SECONDS);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.taos.example;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class RESTConnectExample {
|
||||
// ANCHOR: main
|
||||
public static void main(String[] args) throws SQLException {
|
||||
String jdbcUrl = "jdbc:TAOS-RS://localhost:6041?user=root&password=taosdata";
|
||||
Connection conn = DriverManager.getConnection(jdbcUrl);
|
||||
System.out.println("Connected");
|
||||
conn.close();
|
||||
}
|
||||
// ANCHOR_END: main
|
||||
}
|
|
@ -0,0 +1,74 @@
|
|||
package com.taos.example;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public class RestInsertExample {
|
||||
private static Connection getConnection() throws SQLException {
|
||||
String jdbcUrl = "jdbc:TAOS-RS://localhost:6041?user=root&password=taosdata";
|
||||
return DriverManager.getConnection(jdbcUrl);
|
||||
}
|
||||
|
||||
private static List<String> getRawData() {
|
||||
return Arrays.asList(
|
||||
"d1001,2018-10-03 14:38:05.000,10.30000,219,0.31000,Beijing.Chaoyang,2",
|
||||
"d1001,2018-10-03 14:38:15.000,12.60000,218,0.33000,Beijing.Chaoyang,2",
|
||||
"d1001,2018-10-03 14:38:16.800,12.30000,221,0.31000,Beijing.Chaoyang,2",
|
||||
"d1002,2018-10-03 14:38:16.650,10.30000,218,0.25000,Beijing.Chaoyang,3",
|
||||
"d1003,2018-10-03 14:38:05.500,11.80000,221,0.28000,Beijing.Haidian,2",
|
||||
"d1003,2018-10-03 14:38:16.600,13.40000,223,0.29000,Beijing.Haidian,2",
|
||||
"d1004,2018-10-03 14:38:05.000,10.80000,223,0.29000,Beijing.Haidian,3",
|
||||
"d1004,2018-10-03 14:38:06.500,11.50000,221,0.35000,Beijing.Haidian,3"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* The generated SQL is:
|
||||
* INSERT INTO power.d1001 USING power.meters TAGS(Beijing.Chaoyang, 2) VALUES('2018-10-03 14:38:05.000',10.30000,219,0.31000)
|
||||
* power.d1001 USING power.meters TAGS(Beijing.Chaoyang, 2) VALUES('2018-10-03 14:38:15.000',12.60000,218,0.33000)
|
||||
* power.d1001 USING power.meters TAGS(Beijing.Chaoyang, 2) VALUES('2018-10-03 14:38:16.800',12.30000,221,0.31000)
|
||||
* power.d1002 USING power.meters TAGS(Beijing.Chaoyang, 3) VALUES('2018-10-03 14:38:16.650',10.30000,218,0.25000)
|
||||
* power.d1003 USING power.meters TAGS(Beijing.Haidian, 2) VALUES('2018-10-03 14:38:05.500',11.80000,221,0.28000)
|
||||
* power.d1003 USING power.meters TAGS(Beijing.Haidian, 2) VALUES('2018-10-03 14:38:16.600',13.40000,223,0.29000)
|
||||
* power.d1004 USING power.meters TAGS(Beijing.Haidian, 3) VALUES('2018-10-03 14:38:05.000',10.80000,223,0.29000)
|
||||
* power.d1004 USING power.meters TAGS(Beijing.Haidian, 3) VALUES('2018-10-03 14:38:06.500',11.50000,221,0.35000)
|
||||
*/
|
||||
private static String getSQL() {
|
||||
StringBuilder sb = new StringBuilder("INSERT INTO ");
|
||||
for (String line : getRawData()) {
|
||||
String[] ps = line.split(",");
|
||||
sb.append("power." + ps[0]).append(" USING power.meters TAGS(")
|
||||
.append(ps[5]).append(", ") // tag: location
|
||||
.append(ps[6]) // tag: groupId
|
||||
.append(") VALUES(")
|
||||
.append('\'').append(ps[1]).append('\'').append(",") // ts
|
||||
.append(ps[2]).append(",") // current
|
||||
.append(ps[3]).append(",") // voltage
|
||||
.append(ps[4]).append(") "); // phase
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static void insertData() throws SQLException {
|
||||
try (Connection conn = getConnection()) {
|
||||
try (Statement stmt = conn.createStatement()) {
|
||||
stmt.execute("CREATE DATABASE power KEEP 3650");
|
||||
stmt.execute("CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) " +
|
||||
"TAGS (location BINARY(64), groupId INT)");
|
||||
String sql = getSQL();
|
||||
int rowCount = stmt.executeUpdate(sql);
|
||||
System.out.println("rowCount=" + rowCount); // rowCount=8
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws SQLException {
|
||||
insertData();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
package com.taos.example;
|
||||
|
||||
import java.sql.*;
|
||||
|
||||
public class RestQueryExample {
|
||||
private static Connection getConnection() throws SQLException {
|
||||
String jdbcUrl = "jdbc:TAOS-RS://localhost:6041/power?user=root&password=taosdata";
|
||||
return DriverManager.getConnection(jdbcUrl);
|
||||
}
|
||||
|
||||
private static void printRow(ResultSet rs) throws SQLException {
|
||||
ResultSetMetaData meta = rs.getMetaData();
|
||||
for (int i = 1; i <= meta.getColumnCount(); i++) {
|
||||
String value = rs.getString(i);
|
||||
System.out.print(value);
|
||||
System.out.print("\t");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
private static void printColName(ResultSet rs) throws SQLException {
|
||||
ResultSetMetaData meta = rs.getMetaData();
|
||||
for (int i = 1; i <= meta.getColumnCount(); i++) {
|
||||
String colLabel = meta.getColumnLabel(i);
|
||||
System.out.print(colLabel);
|
||||
System.out.print("\t");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
private static void processResult(ResultSet rs) throws SQLException {
|
||||
printColName(rs);
|
||||
while (rs.next()) {
|
||||
printRow(rs);
|
||||
}
|
||||
}
|
||||
|
||||
private static void queryData() throws SQLException {
|
||||
try (Connection conn = getConnection()) {
|
||||
try (Statement stmt = conn.createStatement()) {
|
||||
ResultSet rs = stmt.executeQuery("SELECT AVG(voltage) FROM meters GROUP BY location");
|
||||
processResult(rs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws SQLException {
|
||||
queryData();
|
||||
}
|
||||
}
|
||||
|
||||
// possible output:
|
||||
// avg(voltage) location
|
||||
// 222.0 Beijing.Haidian
|
||||
// 219.0 Beijing.Chaoyang
|
|
@ -0,0 +1,84 @@
|
|||
package com.taos.example;
|
||||
|
||||
import com.taosdata.jdbc.TSDBPreparedStatement;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class StmtInsertExample {
|
||||
private static ArrayList<Long> tsToLongArray(String ts) {
|
||||
ArrayList<Long> result = new ArrayList<>();
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
|
||||
LocalDateTime localDateTime = LocalDateTime.parse(ts, formatter);
|
||||
result.add(localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli());
|
||||
return result;
|
||||
}
|
||||
|
||||
private static <T> ArrayList<T> toArray(T v) {
|
||||
ArrayList<T> result = new ArrayList<>();
|
||||
result.add(v);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static List<String> getRawData() {
|
||||
return Arrays.asList(
|
||||
"d1001,2018-10-03 14:38:05.000,10.30000,219,0.31000,Beijing.Chaoyang,2",
|
||||
"d1001,2018-10-03 14:38:15.000,12.60000,218,0.33000,Beijing.Chaoyang,2",
|
||||
"d1001,2018-10-03 14:38:16.800,12.30000,221,0.31000,Beijing.Chaoyang,2",
|
||||
"d1002,2018-10-03 14:38:16.650,10.30000,218,0.25000,Beijing.Chaoyang,3",
|
||||
"d1003,2018-10-03 14:38:05.500,11.80000,221,0.28000,Beijing.Haidian,2",
|
||||
"d1003,2018-10-03 14:38:16.600,13.40000,223,0.29000,Beijing.Haidian,2",
|
||||
"d1004,2018-10-03 14:38:05.000,10.80000,223,0.29000,Beijing.Haidian,3",
|
||||
"d1004,2018-10-03 14:38:06.500,11.50000,221,0.35000,Beijing.Haidian,3"
|
||||
);
|
||||
}
|
||||
|
||||
private static Connection getConnection() throws SQLException {
|
||||
String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata";
|
||||
return DriverManager.getConnection(jdbcUrl);
|
||||
}
|
||||
|
||||
private static void createTable(Connection conn) throws SQLException {
|
||||
try (Statement stmt = conn.createStatement()) {
|
||||
stmt.execute("CREATE DATABASE power KEEP 3650");
|
||||
stmt.executeUpdate("USE power");
|
||||
stmt.execute("CREATE STABLE meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) " +
|
||||
"TAGS (location BINARY(64), groupId INT)");
|
||||
}
|
||||
}
|
||||
|
||||
private static void insertData() throws SQLException {
|
||||
try (Connection conn = getConnection()) {
|
||||
createTable(conn);
|
||||
String psql = "INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)";
|
||||
try (TSDBPreparedStatement pst = (TSDBPreparedStatement) conn.prepareStatement(psql)) {
|
||||
for (String line : getRawData()) {
|
||||
String[] ps = line.split(",");
|
||||
// bind table name and tags
|
||||
pst.setTableName(ps[0]);
|
||||
pst.setTagString(0, ps[5]);
|
||||
pst.setTagInt(1, Integer.valueOf(ps[6]));
|
||||
// bind values
|
||||
pst.setTimestamp(0, tsToLongArray(ps[1])); //ps[1] looks like: 2018-10-03 14:38:05.000
|
||||
pst.setFloat(1, toArray(Float.valueOf(ps[2])));
|
||||
pst.setInt(2, toArray(Integer.valueOf(ps[3])));
|
||||
pst.setFloat(3, toArray(Float.valueOf(ps[4])));
|
||||
pst.columnDataAddBatch();
|
||||
}
|
||||
pst.columnDataExecuteBatch();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws SQLException {
|
||||
insertData();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,65 @@
|
|||
package com.taos.example;
|
||||
|
||||
import com.taosdata.jdbc.TSDBConnection;
|
||||
import com.taosdata.jdbc.TSDBDriver;
|
||||
import com.taosdata.jdbc.TSDBResultSet;
|
||||
import com.taosdata.jdbc.TSDBSubscribe;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class SubscribeDemo {
|
||||
private static final String topic = "topic-meter-current-bg-10";
|
||||
private static final String sql = "select * from meters where current > 10";
|
||||
|
||||
public static void main(String[] args) {
|
||||
Connection connection = null;
|
||||
TSDBSubscribe subscribe = null;
|
||||
|
||||
try {
|
||||
Class.forName("com.taosdata.jdbc.TSDBDriver");
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
|
||||
properties.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
|
||||
String jdbcUrl = "jdbc:TAOS://127.0.0.1:6030/power?user=root&password=taosdata";
|
||||
connection = DriverManager.getConnection(jdbcUrl, properties);
|
||||
// create subscribe
|
||||
subscribe = ((TSDBConnection) connection).subscribe(topic, sql, true);
|
||||
int count = 0;
|
||||
while (count < 10) {
|
||||
// wait 1 second to avoid frequent calls to consume
|
||||
TimeUnit.SECONDS.sleep(1);
|
||||
// consume
|
||||
TSDBResultSet resultSet = subscribe.consume();
|
||||
if (resultSet == null) {
|
||||
continue;
|
||||
}
|
||||
ResultSetMetaData metaData = resultSet.getMetaData();
|
||||
while (resultSet.next()) {
|
||||
int columnCount = metaData.getColumnCount();
|
||||
for (int i = 1; i <= columnCount; i++) {
|
||||
System.out.print(metaData.getColumnLabel(i) + ": " + resultSet.getString(i) + "\t");
|
||||
}
|
||||
System.out.println();
|
||||
count++;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
try {
|
||||
if (null != subscribe)
|
||||
// close subscribe
|
||||
subscribe.close(true);
|
||||
if (connection != null)
|
||||
connection.close();
|
||||
} catch (SQLException throwable) {
|
||||
throwable.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package com.taos.example;
|
||||
|
||||
import com.taosdata.jdbc.SchemalessWriter;
|
||||
import com.taosdata.jdbc.enums.SchemalessProtocolType;
|
||||
import com.taosdata.jdbc.enums.SchemalessTimestampType;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
public class TelnetLineProtocolExample {
|
||||
// format: <metric> <timestamp> <value> <tagk_1>=<tagv_1>[ <tagk_n>=<tagv_n>]
|
||||
private static String[] lines = { "meters.current 1648432611249 10.3 location=Beijing.Chaoyang groupid=2",
|
||||
"meters.current 1648432611250 12.6 location=Beijing.Chaoyang groupid=2",
|
||||
"meters.current 1648432611249 10.8 location=Beijing.Haidian groupid=3",
|
||||
"meters.current 1648432611250 11.3 location=Beijing.Haidian groupid=3",
|
||||
"meters.voltage 1648432611249 219 location=Beijing.Chaoyang groupid=2",
|
||||
"meters.voltage 1648432611250 218 location=Beijing.Chaoyang groupid=2",
|
||||
"meters.voltage 1648432611249 221 location=Beijing.Haidian groupid=3",
|
||||
"meters.voltage 1648432611250 217 location=Beijing.Haidian groupid=3",
|
||||
};
|
||||
|
||||
private static Connection getConnection() throws SQLException {
|
||||
String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata";
|
||||
return DriverManager.getConnection(jdbcUrl);
|
||||
}
|
||||
|
||||
private static void createDatabase(Connection conn) throws SQLException {
|
||||
try (Statement stmt = conn.createStatement()) {
|
||||
// the default precision is ms (microsecond), but we use us(microsecond) here.
|
||||
stmt.execute("CREATE DATABASE IF NOT EXISTS test precision 'us'");
|
||||
stmt.execute("USE test");
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws SQLException {
|
||||
try (Connection conn = getConnection()) {
|
||||
createDatabase(conn);
|
||||
SchemalessWriter writer = new SchemalessWriter(conn);
|
||||
writer.write(lines, SchemalessProtocolType.TELNET, SchemalessTimestampType.NOT_CONFIGURED);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.taos.example;
|
||||
|
||||
import com.taosdata.jdbc.TSDBDriver;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Properties;
|
||||
|
||||
public class WSConnectExample {
|
||||
// ANCHOR: main
|
||||
public static void main(String[] args) throws SQLException {
|
||||
String jdbcUrl = "jdbc:TAOS-RS://localhost:6041?user=root&password=taosdata";
|
||||
Properties connProps = new Properties();
|
||||
connProps.setProperty(TSDBDriver.PROPERTY_KEY_BATCH_LOAD, "true");
|
||||
Connection conn = DriverManager.getConnection(jdbcUrl, connProps);
|
||||
System.out.println("Connected");
|
||||
conn.close();
|
||||
}
|
||||
// ANCHOR_END: main
|
||||
}
|
|
@ -0,0 +1,91 @@
|
|||
package com.taos.test;
|
||||
|
||||
import com.taos.example.*;
|
||||
import org.junit.FixMethodOrder;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.sql.*;
|
||||
|
||||
@FixMethodOrder
|
||||
public class TestAll {
|
||||
private String[] args = new String[]{};
|
||||
|
||||
public void dropDB(String dbName) throws SQLException {
|
||||
String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata";
|
||||
try (Connection conn = DriverManager.getConnection(jdbcUrl)) {
|
||||
try (Statement stmt = conn.createStatement()) {
|
||||
stmt.execute("drop database if exists " + dbName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void insertData() throws SQLException {
|
||||
String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata";
|
||||
try (Connection conn = DriverManager.getConnection(jdbcUrl)) {
|
||||
try (Statement stmt = conn.createStatement()) {
|
||||
String sql = "INSERT INTO power.d1001 USING power.meters TAGS(Beijing.Chaoyang, 2) VALUES('2018-10-03 14:38:05.000',10.30000,219,0.31000)\n" +
|
||||
" power.d1001 USING power.meters TAGS(Beijing.Chaoyang, 2) VALUES('2018-10-03 15:38:15.000',12.60000,218,0.33000)\n" +
|
||||
" power.d1001 USING power.meters TAGS(Beijing.Chaoyang, 2) VALUES('2018-10-03 15:38:16.800',12.30000,221,0.31000)\n" +
|
||||
" power.d1002 USING power.meters TAGS(Beijing.Chaoyang, 3) VALUES('2018-10-03 15:38:16.650',10.30000,218,0.25000)\n" +
|
||||
" power.d1003 USING power.meters TAGS(Beijing.Haidian, 2) VALUES('2018-10-03 15:38:05.500',11.80000,221,0.28000)\n" +
|
||||
" power.d1003 USING power.meters TAGS(Beijing.Haidian, 2) VALUES('2018-10-03 15:38:16.600',13.40000,223,0.29000)\n" +
|
||||
" power.d1004 USING power.meters TAGS(Beijing.Haidian, 3) VALUES('2018-10-03 15:38:05.000',10.80000,223,0.29000)\n" +
|
||||
" power.d1004 USING power.meters TAGS(Beijing.Haidian, 3) VALUES('2018-10-03 15:38:06.000',10.80000,223,0.29000)\n" +
|
||||
" power.d1004 USING power.meters TAGS(Beijing.Haidian, 3) VALUES('2018-10-03 15:38:07.000',10.80000,223,0.29000)\n" +
|
||||
" power.d1004 USING power.meters TAGS(Beijing.Haidian, 3) VALUES('2018-10-03 15:38:08.500',11.50000,221,0.35000)";
|
||||
|
||||
stmt.execute(sql);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJNIConnect() throws SQLException {
|
||||
JNIConnectExample.main(args);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRestConnect() throws SQLException {
|
||||
RESTConnectExample.main(args);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRestInsert() throws SQLException {
|
||||
dropDB("power");
|
||||
RestInsertExample.main(args);
|
||||
RestQueryExample.main(args);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStmtInsert() throws SQLException {
|
||||
dropDB("power");
|
||||
StmtInsertExample.main(args);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSubscribe() {
|
||||
|
||||
Thread thread = new Thread(() -> {
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
insertData();
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
});
|
||||
thread.start();
|
||||
SubscribeDemo.main(args);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSchemaless() throws SQLException {
|
||||
LineProtocolExample.main(args);
|
||||
TelnetLineProtocolExample.main(args);
|
||||
// for json protocol, tags may be double type. but for telnet protocol tag must be nchar type.
|
||||
// To avoid type mismatch, we delete database test.
|
||||
dropDB("test");
|
||||
JSONProtocolExample.main(args);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
node_modules
|
||||
package-lock.json
|
||||
yarn-lock.json
|
|
@ -0,0 +1,21 @@
|
|||
const taos = require("td2.0-connector");
|
||||
const conn = taos.connect({ host: "localhost", database: "power" });
|
||||
const cursor = conn.cursor();
|
||||
|
||||
function queryExample() {
|
||||
cursor
|
||||
.query("SELECT ts, current FROM meters LIMIT 2")
|
||||
.execute_a()
|
||||
.then((result) => {
|
||||
result.pretty();
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
queryExample();
|
||||
} finally {
|
||||
setTimeout(() => {
|
||||
conn.close();
|
||||
}, 2000);
|
||||
}
|
||||
// bug here: jira 14506
|
|
@ -0,0 +1,13 @@
|
|||
const taos = require("td2.0-connector");
|
||||
|
||||
var conn = taos.connect({
|
||||
host: "localhost",
|
||||
port: 6030,
|
||||
user: "root",
|
||||
password: "taosdata",
|
||||
});
|
||||
conn.close();
|
||||
|
||||
// run with: node connect.js
|
||||
// output:
|
||||
// Successfully connected to TDengine
|
|
@ -0,0 +1,34 @@
|
|||
const taos = require("td2.0-connector");
|
||||
|
||||
const conn = taos.connect({
|
||||
host: "localhost",
|
||||
});
|
||||
|
||||
const cursor = conn.cursor();
|
||||
|
||||
function createDatabase() {
|
||||
cursor.execute("CREATE DATABASE test");
|
||||
cursor.execute("USE test");
|
||||
}
|
||||
|
||||
function insertData() {
|
||||
const lines = [
|
||||
"meters,location=Beijing.Haidian,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249",
|
||||
"meters,location=Beijing.Haidian,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611250",
|
||||
"meters,location=Beijing.Haidian,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249",
|
||||
"meters,location=Beijing.Haidian,groupid=3 current=11.3,voltage=221,phase=0.35 1648432611250",
|
||||
];
|
||||
cursor.schemalessInsert(
|
||||
lines,
|
||||
taos.SCHEMALESS_PROTOCOL.TSDB_SML_LINE_PROTOCOL,
|
||||
taos.SCHEMALESS_PRECISION.TSDB_SML_TIMESTAMP_MILLI_SECONDS
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
createDatabase();
|
||||
insertData();
|
||||
} finally {
|
||||
cursor.close();
|
||||
conn.close();
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
const taos = require("td2.0-connector");
|
||||
|
||||
const conn = taos.connect({
|
||||
host: "localhost",
|
||||
});
|
||||
|
||||
const cursor = conn.cursor();
|
||||
try {
|
||||
cursor.execute("CREATE DATABASE power");
|
||||
cursor.execute("USE power");
|
||||
cursor.execute(
|
||||
"CREATE STABLE meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)"
|
||||
);
|
||||
var sql = `INSERT INTO power.d1001 USING power.meters TAGS(Beijing.Chaoyang, 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(Beijing.Chaoyang, 3) VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000)
|
||||
power.d1003 USING power.meters TAGS(Beijing.Haidian, 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(Beijing.Haidian, 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)`;
|
||||
cursor.execute(sql);
|
||||
} finally {
|
||||
cursor.close();
|
||||
conn.close();
|
||||
}
|
||||
|
||||
// run with: node insert_example.js
|
||||
// output:
|
||||
// Successfully connected to TDengine
|
||||
// Query OK, 0 row(s) affected (0.00509570s)
|
||||
// Query OK, 0 row(s) affected (0.00130880s)
|
||||
// Query OK, 0 row(s) affected (0.00467900s)
|
||||
// Query OK, 8 row(s) affected (0.04043550s)
|
||||
// Connection is closed
|
|
@ -0,0 +1,53 @@
|
|||
const taos = require("td2.0-connector");
|
||||
|
||||
const conn = taos.connect({
|
||||
host: "localhost",
|
||||
});
|
||||
|
||||
const cursor = conn.cursor();
|
||||
|
||||
function prepareSTable() {
|
||||
cursor.execute("CREATE DATABASE power");
|
||||
cursor.execute("USE power");
|
||||
cursor.execute(
|
||||
"CREATE STABLE meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)"
|
||||
);
|
||||
}
|
||||
|
||||
//ANCHOR: insertData
|
||||
function insertData() {
|
||||
// init
|
||||
cursor.stmtInit();
|
||||
// prepare
|
||||
cursor.stmtPrepare(
|
||||
"INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)"
|
||||
);
|
||||
|
||||
// bind table name and tags
|
||||
let tagBind = new taos.TaosBind(2);
|
||||
tagBind.bindBinary("Beijing.Chaoyang");
|
||||
tagBind.bindInt(2);
|
||||
cursor.stmtSetTbnameTags("d1001", tagBind.getBind());
|
||||
|
||||
// bind values
|
||||
let valueBind = new taos.TaosMultiBindArr(4);
|
||||
valueBind.multiBindTimestamp([1648432611249, 1648432611749]);
|
||||
valueBind.multiBindFloat([10.3, 12.6]);
|
||||
valueBind.multiBindInt([219, 218]);
|
||||
valueBind.multiBindFloat([0.31, 0.33]);
|
||||
cursor.stmtBindParamBatch(valueBind.getMultiBindArr());
|
||||
cursor.stmtAddBatch();
|
||||
|
||||
// execute
|
||||
cursor.stmtExecute();
|
||||
cursor.stmtClose();
|
||||
}
|
||||
//ANCHOR_END: insertData
|
||||
|
||||
try {
|
||||
prepareSTable();
|
||||
insertData();
|
||||
} finally {
|
||||
cursor.close();
|
||||
conn.close();
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
const taos = require("td2.0-connector");
|
||||
|
||||
const conn = taos.connect({
|
||||
host: "localhost",
|
||||
});
|
||||
|
||||
const cursor = conn.cursor();
|
||||
|
||||
function createDatabase() {
|
||||
cursor.execute("CREATE DATABASE test");
|
||||
cursor.execute("USE test");
|
||||
}
|
||||
|
||||
function insertData() {
|
||||
const lines = [
|
||||
{
|
||||
metric: "meters.current",
|
||||
timestamp: 1648432611249,
|
||||
value: 10.3,
|
||||
tags: { location: "Beijing.Chaoyang", groupid: 2 },
|
||||
},
|
||||
{
|
||||
metric: "meters.voltage",
|
||||
timestamp: 1648432611249,
|
||||
value: 219,
|
||||
tags: { location: "Beijing.Haidian", groupid: 1 },
|
||||
},
|
||||
{
|
||||
metric: "meters.current",
|
||||
timestamp: 1648432611250,
|
||||
value: 12.6,
|
||||
tags: { location: "Beijing.Chaoyang", groupid: 2 },
|
||||
},
|
||||
{
|
||||
metric: "meters.voltage",
|
||||
timestamp: 1648432611250,
|
||||
value: 221,
|
||||
tags: { location: "Beijing.Haidian", groupid: 1 },
|
||||
},
|
||||
];
|
||||
|
||||
cursor.schemalessInsert(
|
||||
[JSON.stringify(lines)],
|
||||
taos.SCHEMALESS_PROTOCOL.TSDB_SML_JSON_PROTOCOL,
|
||||
taos.SCHEMALESS_PRECISION.TSDB_SML_TIMESTAMP_NOT_CONFIGURED
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
createDatabase();
|
||||
insertData();
|
||||
} finally {
|
||||
cursor.close();
|
||||
conn.close();
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
const taos = require("td2.0-connector");
|
||||
|
||||
const conn = taos.connect({
|
||||
host: "localhost",
|
||||
});
|
||||
|
||||
const cursor = conn.cursor();
|
||||
|
||||
function createDatabase() {
|
||||
cursor.execute("CREATE DATABASE test");
|
||||
cursor.execute("USE test");
|
||||
}
|
||||
|
||||
function insertData() {
|
||||
const lines = [
|
||||
"meters.current 1648432611249 10.3 location=Beijing.Chaoyang groupid=2",
|
||||
"meters.current 1648432611250 12.6 location=Beijing.Chaoyang groupid=2",
|
||||
"meters.current 1648432611249 10.8 location=Beijing.Haidian groupid=3",
|
||||
"meters.current 1648432611250 11.3 location=Beijing.Haidian groupid=3",
|
||||
"meters.voltage 1648432611249 219 location=Beijing.Chaoyang groupid=2",
|
||||
"meters.voltage 1648432611250 218 location=Beijing.Chaoyang groupid=2",
|
||||
"meters.voltage 1648432611249 221 location=Beijing.Haidian groupid=3",
|
||||
"meters.voltage 1648432611250 217 location=Beijing.Haidian groupid=3",
|
||||
];
|
||||
cursor.schemalessInsert(
|
||||
lines,
|
||||
taos.SCHEMALESS_PROTOCOL.TSDB_SML_TELNET_PROTOCOL,
|
||||
taos.SCHEMALESS_PRECISION.TSDB_SML_TIMESTAMP_NOT_CONFIGURED
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
createDatabase();
|
||||
insertData();
|
||||
} finally {
|
||||
cursor.close();
|
||||
conn.close();
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
const taos = require("td2.0-connector");
|
||||
|
||||
const conn = taos.connect({
|
||||
host: "localhost",
|
||||
});
|
||||
|
||||
const cursor = conn.cursor();
|
||||
|
||||
function prepareSTable() {
|
||||
cursor.execute("CREATE DATABASE power");
|
||||
cursor.execute("USE power");
|
||||
cursor.execute(
|
||||
"CREATE STABLE meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)"
|
||||
);
|
||||
}
|
||||
|
||||
function insertData() {
|
||||
// init
|
||||
cursor.stmtInit();
|
||||
// prepare
|
||||
cursor.stmtPrepare(
|
||||
"INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)"
|
||||
);
|
||||
|
||||
// bind table name and tags
|
||||
let tagBind = new taos.TaosBind(2);
|
||||
tagBind.bindBinary("Beijing.Chaoyang");
|
||||
tagBind.bindInt(2);
|
||||
cursor.stmtSetTbnameTags("d1001", tagBind.getBind());
|
||||
|
||||
// bind values
|
||||
let rows = [
|
||||
[1648432611249, 10.3, 219, 0.31],
|
||||
[1648432611749, 12.6, 218, 0.33],
|
||||
];
|
||||
for (let row of rows) {
|
||||
let valueBind = new taos.TaosBind(4);
|
||||
valueBind.bindTimestamp(row[0]);
|
||||
valueBind.bindFloat(row[1]);
|
||||
valueBind.bindInt(row[2]);
|
||||
valueBind.bindFloat(row[3]);
|
||||
cursor.stmtBindParam(valueBind.getBind());
|
||||
cursor.stmtAddBatch();
|
||||
}
|
||||
|
||||
// execute
|
||||
cursor.stmtExecute();
|
||||
cursor.stmtClose();
|
||||
}
|
||||
|
||||
try {
|
||||
prepareSTable();
|
||||
insertData();
|
||||
} finally {
|
||||
cursor.close();
|
||||
conn.close();
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
const taos = require("td2.0-connector");
|
||||
|
||||
const conn = taos.connect({ host: "localhost", database: "power" });
|
||||
const cursor = conn.cursor();
|
||||
const query = cursor.query("SELECT ts, current FROM meters LIMIT 2");
|
||||
query.execute().then(function (result) {
|
||||
result.pretty();
|
||||
});
|
||||
|
||||
// output:
|
||||
// Successfully connected to TDengine
|
||||
// Query OK, 2 row(s) in set (0.00317767s)
|
||||
|
||||
// ts | current |
|
||||
// =======================================================
|
||||
// 2018-10-03 14:38:05.000 | 10.3 |
|
||||
// 2018-10-03 14:38:15.000 | 12.6 |
|
|
@ -0,0 +1,4 @@
|
|||
const taos = require("td2.0-connector");
|
||||
|
||||
const conn = taos.connect({ host: "localhost", database: "power" });
|
||||
// 未完成
|
|
@ -0,0 +1,10 @@
|
|||
{
|
||||
"name": "examples",
|
||||
"version": "1.0.0",
|
||||
"main": "index.js",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"td2.0-connector": "^2.0.12",
|
||||
"td2.0-rest-connector": "^1.0.0"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
const { options, connect } = require("td2.0-rest-connector");
|
||||
|
||||
async function test() {
|
||||
options.path = "/rest/sqlt";
|
||||
options.host = "localhost";
|
||||
let conn = connect(options);
|
||||
let cursor = conn.cursor();
|
||||
try {
|
||||
let res = await cursor.query("SELECT server_version()");
|
||||
res.toString();
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
}
|
||||
}
|
||||
test();
|
||||
|
||||
// output:
|
||||
// server_version() |
|
||||
// ===================
|
||||
// 2.4.0.12 |
|
|
@ -0,0 +1,20 @@
|
|||
<?php
|
||||
|
||||
use TDengine\Connection;
|
||||
use TDengine\Exception\TDengineException;
|
||||
|
||||
try {
|
||||
// 实例化
|
||||
$host = 'localhost';
|
||||
$port = 6030;
|
||||
$username = 'root';
|
||||
$password = 'taosdata';
|
||||
$dbname = null;
|
||||
$connection = new Connection($host, $port, $username, $password, $dbname);
|
||||
|
||||
// 连接
|
||||
$connection->connect();
|
||||
} catch (TDengineException $e) {
|
||||
// 连接失败捕获异常
|
||||
throw $e;
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
<?php
|
||||
|
||||
use TDengine\Connection;
|
||||
use TDengine\Exception\TDengineException;
|
||||
|
||||
try {
|
||||
// 实例化
|
||||
$host = 'localhost';
|
||||
$port = 6030;
|
||||
$username = 'root';
|
||||
$password = 'taosdata';
|
||||
$dbname = 'power';
|
||||
$connection = new Connection($host, $port, $username, $password, $dbname);
|
||||
|
||||
// 连接
|
||||
$connection->connect();
|
||||
|
||||
// 插入
|
||||
$connection->query('CREATE DATABASE if not exists power');
|
||||
$connection->query('CREATE STABLE if not exists meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)');
|
||||
$resource = $connection->query(<<<'SQL'
|
||||
INSERT INTO power.d1001 USING power.meters TAGS(Beijing.Chaoyang, 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(Beijing.Chaoyang, 3) VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000)
|
||||
power.d1003 USING power.meters TAGS(Beijing.Haidian, 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(Beijing.Haidian, 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)
|
||||
SQL);
|
||||
|
||||
// 影响行数
|
||||
var_dump($resource->affectedRows());
|
||||
} catch (TDengineException $e) {
|
||||
// 捕获异常
|
||||
throw $e;
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
<?php
|
||||
|
||||
use TDengine\Connection;
|
||||
use TDengine\Exception\TDengineException;
|
||||
|
||||
try {
|
||||
// 实例化
|
||||
$host = 'localhost';
|
||||
$port = 6030;
|
||||
$username = 'root';
|
||||
$password = 'taosdata';
|
||||
$dbname = 'power';
|
||||
$connection = new Connection($host, $port, $username, $password, $dbname);
|
||||
|
||||
// 连接
|
||||
$connection->connect();
|
||||
|
||||
// 插入
|
||||
$connection->query('CREATE DATABASE if not exists power');
|
||||
$connection->query('CREATE STABLE if not exists meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)');
|
||||
$stmt = $connection->prepare('INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)');
|
||||
|
||||
// 设置表名和标签
|
||||
$stmt->setTableNameTags('d1001', [
|
||||
// 支持格式同参数绑定
|
||||
[TDengine\TSDB_DATA_TYPE_BINARY, 'Beijing.Chaoyang'],
|
||||
[TDengine\TSDB_DATA_TYPE_INT, 2],
|
||||
]);
|
||||
|
||||
$stmt->bindParams([
|
||||
[TDengine\TSDB_DATA_TYPE_TIMESTAMP, 1648432611249],
|
||||
[TDengine\TSDB_DATA_TYPE_FLOAT, 10.3],
|
||||
[TDengine\TSDB_DATA_TYPE_INT, 219],
|
||||
[TDengine\TSDB_DATA_TYPE_FLOAT, 0.31],
|
||||
]);
|
||||
$stmt->bindParams([
|
||||
[TDengine\TSDB_DATA_TYPE_TIMESTAMP, 1648432611749],
|
||||
[TDengine\TSDB_DATA_TYPE_FLOAT, 12.6],
|
||||
[TDengine\TSDB_DATA_TYPE_INT, 218],
|
||||
[TDengine\TSDB_DATA_TYPE_FLOAT, 0.33],
|
||||
]);
|
||||
$resource = $stmt->execute();
|
||||
|
||||
// 影响行数
|
||||
var_dump($resource->affectedRows());
|
||||
} catch (TDengineException $e) {
|
||||
// 捕获异常
|
||||
throw $e;
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
<?php
|
||||
|
||||
use TDengine\Connection;
|
||||
use TDengine\Exception\TDengineException;
|
||||
|
||||
try {
|
||||
// 实例化
|
||||
$host = 'localhost';
|
||||
$port = 6030;
|
||||
$username = 'root';
|
||||
$password = 'taosdata';
|
||||
$dbname = 'power';
|
||||
$connection = new Connection($host, $port, $username, $password, $dbname);
|
||||
|
||||
// 连接
|
||||
$connection->connect();
|
||||
|
||||
$resource = $connection->query('SELECT ts, current FROM meters LIMIT 2');
|
||||
var_dump($resource->fetch());
|
||||
} catch (TDengineException $e) {
|
||||
// 捕获异常
|
||||
throw $e;
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
.idea
|
|
@ -0,0 +1,72 @@
|
|||
import time
|
||||
from ctypes import *
|
||||
|
||||
from taos import *
|
||||
|
||||
|
||||
def fetch_callback(p_param, p_result, num_of_rows):
|
||||
print("fetched ", num_of_rows, "rows")
|
||||
p = cast(p_param, POINTER(Counter))
|
||||
result = TaosResult(p_result)
|
||||
|
||||
if num_of_rows == 0:
|
||||
print("fetching completed")
|
||||
p.contents.done = True
|
||||
result.close()
|
||||
return
|
||||
if num_of_rows < 0:
|
||||
p.contents.done = True
|
||||
result.check_error(num_of_rows)
|
||||
result.close()
|
||||
return None
|
||||
|
||||
for row in result.rows_iter(num_of_rows):
|
||||
print(row)
|
||||
p.contents.count += result.row_count
|
||||
result.fetch_rows_a(fetch_callback, p_param)
|
||||
|
||||
|
||||
def query_callback(p_param, p_result, code):
|
||||
if p_result is None:
|
||||
return
|
||||
result = TaosResult(p_result)
|
||||
if code == 0:
|
||||
result.fetch_rows_a(fetch_callback, p_param)
|
||||
result.check_error(code)
|
||||
|
||||
|
||||
class Counter(Structure):
|
||||
_fields_ = [("count", c_int), ("done", c_bool)]
|
||||
|
||||
def __str__(self):
|
||||
return "{ count: %d, done: %s }" % (self.count, self.done)
|
||||
|
||||
|
||||
def test_query(conn):
|
||||
counter = Counter(count=0)
|
||||
conn.query_a("select ts, current, voltage from power.meters", query_callback, byref(counter))
|
||||
|
||||
while not counter.done:
|
||||
print(counter)
|
||||
time.sleep(1)
|
||||
print(counter)
|
||||
conn.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_query(connect())
|
||||
|
||||
# possible output:
|
||||
# { count: 0, done: False }
|
||||
# fetched 8 rows
|
||||
# 1538548685000 10.300000 219
|
||||
# 1538548695000 12.600000 218
|
||||
# 1538548696800 12.300000 221
|
||||
# 1538548696650 10.300000 218
|
||||
# 1538548685500 11.800000 221
|
||||
# 1538548696600 13.400000 223
|
||||
# 1538548685500 10.800000 223
|
||||
# 1538548686500 11.500000 221
|
||||
# fetched 0 rows
|
||||
# fetching completed
|
||||
# { count: 8, done: True }
|
|
@ -0,0 +1,60 @@
|
|||
import taos
|
||||
from datetime import datetime
|
||||
|
||||
# note: lines have already been sorted by table name
|
||||
lines = [('d1001', '2018-10-03 14:38:05.000', 10.30000, 219, 0.31000, 'Beijing.Chaoyang', 2),
|
||||
('d1001', '2018-10-03 14:38:15.000', 12.60000, 218, 0.33000, 'Beijing.Chaoyang', 2),
|
||||
('d1001', '2018-10-03 14:38:16.800', 12.30000, 221, 0.31000, 'Beijing.Chaoyang', 2),
|
||||
('d1002', '2018-10-03 14:38:16.650', 10.30000, 218, 0.25000, 'Beijing.Chaoyang', 3),
|
||||
('d1003', '2018-10-03 14:38:05.500', 11.80000, 221, 0.28000, 'Beijing.Haidian', 2),
|
||||
('d1003', '2018-10-03 14:38:16.600', 13.40000, 223, 0.29000, 'Beijing.Haidian', 2),
|
||||
('d1004', '2018-10-03 14:38:05.000', 10.80000, 223, 0.29000, 'Beijing.Haidian', 3),
|
||||
('d1004', '2018-10-03 14:38:06.500', 11.50000, 221, 0.35000, 'Beijing.Haidian', 3)]
|
||||
|
||||
|
||||
def get_ts(ts: str):
|
||||
dt = datetime.strptime(ts, '%Y-%m-%d %H:%M:%S.%f')
|
||||
return int(dt.timestamp() * 1000)
|
||||
|
||||
|
||||
def create_stable():
|
||||
conn = taos.connect()
|
||||
try:
|
||||
conn.execute("CREATE DATABASE power")
|
||||
conn.execute("CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) "
|
||||
"TAGS (location BINARY(64), groupId INT)")
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def bind_row_by_row(stmt: taos.TaosStmt):
|
||||
tb_name = None
|
||||
for row in lines:
|
||||
if tb_name != row[0]:
|
||||
tb_name = row[0]
|
||||
tags: taos.TaosBind = taos.new_bind_params(2) # 2 is count of tags
|
||||
tags[0].binary(row[5]) # location
|
||||
tags[1].int(row[6]) # groupId
|
||||
stmt.set_tbname_tags(tb_name, tags)
|
||||
values: taos.TaosBind = taos.new_bind_params(4) # 4 is count of columns
|
||||
values[0].timestamp(get_ts(row[1]))
|
||||
values[1].float(row[2])
|
||||
values[2].int(row[3])
|
||||
values[3].float(row[4])
|
||||
stmt.bind_param(values)
|
||||
|
||||
|
||||
def insert_data():
|
||||
conn = taos.connect(database="power")
|
||||
try:
|
||||
stmt = conn.statement("INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)")
|
||||
bind_row_by_row(stmt)
|
||||
stmt.execute()
|
||||
stmt.close()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
create_stable()
|
||||
insert_data()
|
|
@ -0,0 +1,19 @@
|
|||
import pandas
|
||||
from sqlalchemy import create_engine
|
||||
|
||||
engine = create_engine("taos://root:taosdata@localhost:6030/power")
|
||||
df = pandas.read_sql("SELECT * FROM meters", engine)
|
||||
|
||||
# print index
|
||||
print(df.index)
|
||||
# print data type of element in ts column
|
||||
print(type(df.ts[0]))
|
||||
print(df.head(3))
|
||||
|
||||
# output:
|
||||
# RangeIndex(start=0, stop=8, step=1)
|
||||
# <class 'pandas._libs.tslibs.timestamps.Timestamp'>
|
||||
# ts current voltage phase location groupid
|
||||
# 0 2018-10-03 14:38:05.000 10.3 219 0.31 beijing.chaoyang 2
|
||||
# 1 2018-10-03 14:38:15.000 12.6 218 0.33 beijing.chaoyang 2
|
||||
# 2 2018-10-03 14:38:16.800 12.3 221 0.31 beijing.chaoyang 2
|
|
@ -0,0 +1,19 @@
|
|||
import pandas
|
||||
from sqlalchemy import create_engine
|
||||
|
||||
engine = create_engine("taosrest://root:taosdata@localhost:6041")
|
||||
df: pandas.DataFrame = pandas.read_sql("SELECT * FROM power.meters", engine)
|
||||
|
||||
# print index
|
||||
print(df.index)
|
||||
# print data type of element in ts column
|
||||
print(type(df.ts[0]))
|
||||
print(df.head(3))
|
||||
|
||||
# output:
|
||||
# <class 'datetime.datetime'>
|
||||
# RangeIndex(start=0, stop=8, step=1)
|
||||
# ts current ... location groupid
|
||||
# 0 2018-10-03 14:38:05+08:00 10.3 ... beijing.chaoyang 2
|
||||
# 1 2018-10-03 14:38:15+08:00 12.6 ... beijing.chaoyang 2
|
||||
# 2 2018-10-03 14:38:16.800000+08:00 12.3 ... beijing.chaoyang 2
|
|
@ -0,0 +1,19 @@
|
|||
import taos
|
||||
|
||||
|
||||
def test_connection():
|
||||
# all parameters are optional.
|
||||
# if database is specified,
|
||||
# then it must exist.
|
||||
conn = taos.connect(host="localhost",
|
||||
port=6030,
|
||||
user="root",
|
||||
password="taosdata",
|
||||
database="log")
|
||||
print('client info:', conn.client_info)
|
||||
print('server info:', conn.server_info)
|
||||
conn.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_connection()
|
|
@ -0,0 +1,20 @@
|
|||
import taos
|
||||
|
||||
conn: taos.TaosConnection = taos.connect(host="localhost",
|
||||
user="root",
|
||||
password="taosdata",
|
||||
database="test",
|
||||
port=6030,
|
||||
config="/etc/taos", # for windows the default value is C:\TDengine\cfg
|
||||
timezone="Asia/Shanghai") # default your host's timezone
|
||||
|
||||
server_version = conn.server_info
|
||||
print("server_version", server_version)
|
||||
client_version = conn.client_info
|
||||
print("client_version", client_version) # 2.4.0.16
|
||||
|
||||
conn.close()
|
||||
|
||||
# possible output:
|
||||
# 2.4.0.16
|
||||
# 2.4.0.16
|
|
@ -0,0 +1,45 @@
|
|||
# ANCHOR: connect
|
||||
from taosrest import connect, TaosRestConnection, TaosRestCursor
|
||||
|
||||
conn: TaosRestConnection = connect(host="localhost",
|
||||
user="root",
|
||||
password="taosdata",
|
||||
port=6041,
|
||||
timeout=30)
|
||||
|
||||
# ANCHOR_END: connect
|
||||
# ANCHOR: basic
|
||||
# create STable
|
||||
cursor: TaosRestCursor = conn.cursor()
|
||||
cursor.execute("DROP DATABASE IF EXISTS power")
|
||||
cursor.execute("CREATE DATABASE power")
|
||||
cursor.execute("CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)")
|
||||
|
||||
# insert data
|
||||
cursor.execute("""INSERT INTO power.d1001 USING power.meters TAGS(Beijing.Chaoyang, 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(Beijing.Chaoyang, 3) VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000)
|
||||
power.d1003 USING power.meters TAGS(Beijing.Haidian, 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(Beijing.Haidian, 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)""")
|
||||
print("inserted row count:", cursor.rowcount)
|
||||
|
||||
# query data
|
||||
cursor.execute("SELECT * FROM power.meters LIMIT 3")
|
||||
# get total rows
|
||||
print("queried row count:", cursor.rowcount)
|
||||
# get column names from cursor
|
||||
column_names = [meta[0] for meta in cursor.description]
|
||||
# get rows
|
||||
data: list[tuple] = cursor.fetchall()
|
||||
print(column_names)
|
||||
for row in data:
|
||||
print(row)
|
||||
|
||||
# output:
|
||||
# inserted row count: 8
|
||||
# queried row count: 3
|
||||
# ['ts', 'current', 'voltage', 'phase', 'location', 'groupid']
|
||||
# [datetime.datetime(2018, 10, 3, 14, 38, 5, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800), '+08:00')), 10.3, 219, 0.31, 'beijing.chaoyang', 2]
|
||||
# [datetime.datetime(2018, 10, 3, 14, 38, 15, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800), '+08:00')), 12.6, 218, 0.33, 'beijing.chaoyang', 2]
|
||||
# [datetime.datetime(2018, 10, 3, 14, 38, 16, 800000, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800), '+08:00')), 12.3, 221, 0.31, 'beijing.chaoyang', 2]
|
||||
|
||||
# ANCHOR_END: basic
|
|
@ -0,0 +1,45 @@
|
|||
import taos
|
||||
|
||||
# ANCHOR: insert
|
||||
conn = taos.connect()
|
||||
# Execute a sql, ignore the result set, just get affected rows. It's useful for DDL and DML statement.
|
||||
conn.execute("DROP DATABASE IF EXISTS test")
|
||||
conn.execute("CREATE DATABASE test")
|
||||
# change database. same as execute "USE db"
|
||||
conn.select_db("test")
|
||||
conn.execute("CREATE STABLE weather(ts TIMESTAMP, temperature FLOAT) TAGS (location INT)")
|
||||
affected_row: int = conn.execute("INSERT INTO t1 USING weather TAGS(1) VALUES (now, 23.5) (now+1m, 23.5) (now+2m 24.4)")
|
||||
print("affected_row", affected_row)
|
||||
# output:
|
||||
# affected_row 3
|
||||
# ANCHOR_END: insert
|
||||
|
||||
# ANCHOR: query
|
||||
# Execute a sql and get its result set. It's useful for SELECT statement
|
||||
result: taos.TaosResult = conn.query("SELECT * from weather")
|
||||
|
||||
# Get fields from result
|
||||
fields: taos.field.TaosFields = result.fields
|
||||
for field in fields:
|
||||
print(field) # {name: ts, type: 9, bytes: 8}
|
||||
|
||||
# output:
|
||||
# {name: ts, type: 9, bytes: 8}
|
||||
# {name: temperature, type: 6, bytes: 4}
|
||||
# {name: location, type: 4, bytes: 4}
|
||||
|
||||
# Get data from result as list of tuple
|
||||
data = result.fetch_all()
|
||||
print(data)
|
||||
# output:
|
||||
# [(datetime.datetime(2022, 4, 27, 9, 4, 25, 367000), 23.5, 1), (datetime.datetime(2022, 4, 27, 9, 5, 25, 367000), 23.5, 1), (datetime.datetime(2022, 4, 27, 9, 6, 25, 367000), 24.399999618530273, 1)]
|
||||
|
||||
# Or get data from result as a list of dict
|
||||
# map_data = result.fetch_all_into_dict()
|
||||
# print(map_data)
|
||||
# output:
|
||||
# [{'ts': datetime.datetime(2022, 4, 27, 9, 1, 15, 343000), 'temperature': 23.5, 'location': 1}, {'ts': datetime.datetime(2022, 4, 27, 9, 2, 15, 343000), 'temperature': 23.5, 'location': 1}, {'ts': datetime.datetime(2022, 4, 27, 9, 3, 15, 343000), 'temperature': 24.399999618530273, 'location': 1}]
|
||||
# ANCHOR_END: query
|
||||
|
||||
|
||||
conn.close()
|
|
@ -0,0 +1,32 @@
|
|||
import taos
|
||||
|
||||
conn = taos.connect()
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute("DROP DATABASE IF EXISTS test")
|
||||
cursor.execute("CREATE DATABASE test")
|
||||
cursor.execute("USE test")
|
||||
cursor.execute("CREATE STABLE weather(ts TIMESTAMP, temperature FLOAT) TAGS (location INT)")
|
||||
|
||||
for i in range(1000):
|
||||
location = str(i % 10)
|
||||
tb = "t" + location
|
||||
cursor.execute(f"INSERT INTO {tb} USING weather TAGS({location}) VALUES (now+{i}a, 23.5) (now+{i + 1}a, 23.5)")
|
||||
|
||||
cursor.execute("SELECT count(*) FROM weather")
|
||||
data = cursor.fetchall()
|
||||
print("count:", data[0][0])
|
||||
cursor.execute("SELECT tbname, * FROM weather LIMIT 2")
|
||||
col_names = [meta[0] for meta in cursor.description]
|
||||
print(col_names)
|
||||
rows = cursor.fetchall()
|
||||
print(rows)
|
||||
|
||||
cursor.close()
|
||||
conn.close()
|
||||
|
||||
# output:
|
||||
# count: 2000
|
||||
# ['tbname', 'ts', 'temperature', 'location']
|
||||
# row_count: -1
|
||||
# [('t0', datetime.datetime(2022, 4, 27, 14, 54, 24, 392000), 23.5, 0), ('t0', datetime.datetime(2022, 4, 27, 14, 54, 24, 393000), 23.5, 0)]
|
|
@ -0,0 +1,19 @@
|
|||
import taos
|
||||
|
||||
try:
|
||||
conn = taos.connect()
|
||||
conn.execute("CREATE TABLE 123") # wrong sql
|
||||
except taos.Error as e:
|
||||
print(e)
|
||||
print("exception class: ", e.__class__.__name__)
|
||||
print("error number:", e.errno)
|
||||
print("error message:", e.msg)
|
||||
except BaseException as other:
|
||||
print("exception occur")
|
||||
print(other)
|
||||
|
||||
# output:
|
||||
# [0x0216]: syntax error near 'Incomplete SQL statement'
|
||||
# exception class: ProgrammingError
|
||||
# error number: -2147483114
|
||||
# error message: syntax error near 'Incomplete SQL statement'
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue