From f82d830734ef2246e4178995a0dd26939e01728e Mon Sep 17 00:00:00 2001 From: gccgdb1234 Date: Sat, 21 May 2022 11:11:57 +0800 Subject: [PATCH] docs: copy docs-examples from 2.6 to 3.0 --- docs-examples/.gitignore | 3 + docs-examples/.gitignre | 2 + docs-examples/R/connect_native.r | 16 ++ docs-examples/R/connect_rest.r | 12 + docs-examples/c/.gitignore | 3 + docs-examples/c/async_query_example.c | 195 ++++++++++++++ docs-examples/c/connect_example.c | 24 ++ docs-examples/c/error_handle_example.c | 24 ++ docs-examples/c/insert_example.c | 51 ++++ docs-examples/c/json_protocol_example.c | 52 ++++ docs-examples/c/line_example.c | 47 ++++ docs-examples/c/multi_bind_example.c | 147 +++++++++++ docs-examples/c/query_example.c | 143 +++++++++++ docs-examples/c/stmt_example.c | 141 +++++++++++ docs-examples/c/subscribe_demo.c | 66 +++++ docs-examples/c/telnet_line_example.c | 54 ++++ docs-examples/csharp/.gitignore | 4 + docs-examples/csharp/AsyncQueryExample.cs | 238 ++++++++++++++++++ docs-examples/csharp/ConnectExample.cs | 29 +++ docs-examples/csharp/InfluxDBLineExample.cs | 77 ++++++ docs-examples/csharp/OptsJsonExample.cs | 76 ++++++ docs-examples/csharp/OptsTelnetExample.cs | 80 ++++++ docs-examples/csharp/QueryExample.cs | 162 ++++++++++++ docs-examples/csharp/SQLInsertExample.cs | 69 +++++ docs-examples/csharp/StmtInsertExample.cs | 115 +++++++++ docs-examples/csharp/SubscribeDemo.cs | 12 + docs-examples/csharp/asyncquery.csproj | 15 ++ docs-examples/csharp/connect.csproj | 15 ++ docs-examples/csharp/influxdbline.csproj | 15 ++ docs-examples/csharp/optsjson.csproj | 15 ++ docs-examples/csharp/optstelnet.csproj | 15 ++ docs-examples/csharp/query.csproj | 15 ++ docs-examples/csharp/sqlinsert.csproj | 15 ++ docs-examples/csharp/stmtinsert.csproj | 15 ++ docs-examples/csharp/subscribe.csproj | 15 ++ docs-examples/go/.gitignore | 3 + docs-examples/go/connect/afconn/main.go | 17 ++ docs-examples/go/connect/cgoexample/main.go | 23 ++ docs-examples/go/connect/restexample/main.go | 23 ++ docs-examples/go/connect/wrapper/main.go | 17 ++ docs-examples/go/go.mod | 6 + docs-examples/go/insert/json/main.go | 37 +++ docs-examples/go/insert/line/main.go | 38 +++ docs-examples/go/insert/stmt/main.go | 73 ++++++ docs-examples/go/insert/telnet/main.go | 42 ++++ docs-examples/go/query/async/main.go | 7 + docs-examples/go/query/sync/main.go | 38 +++ docs-examples/go/rest/opentsdbjson/main.go | 45 ++++ docs-examples/go/sub/main.go | 53 ++++ docs-examples/java/.gitignore | 2 + docs-examples/java/pom.xml | 35 +++ .../com/taos/example/JNIConnectExample.java | 25 ++ .../com/taos/example/JSONProtocolExample.java | 40 +++ .../com/taos/example/LineProtocolExample.java | 42 ++++ .../com/taos/example/RESTConnectExample.java | 16 ++ .../com/taos/example/RestInsertExample.java | 74 ++++++ .../com/taos/example/RestQueryExample.java | 55 ++++ .../com/taos/example/StmtInsertExample.java | 84 +++++++ .../java/com/taos/example/SubscribeDemo.java | 65 +++++ .../example/TelnetLineProtocolExample.java | 45 ++++ .../com/taos/example/WSConnectExample.java | 21 ++ .../src/test/java/com/taos/test/TestAll.java | 91 +++++++ docs-examples/node/.gitignore | 3 + .../node/nativeexample/async_query_example.js | 21 ++ docs-examples/node/nativeexample/connect.js | 13 + .../nativeexample/influxdb_line_example.js | 34 +++ .../node/nativeexample/insert_example.js | 31 +++ .../node/nativeexample/multi_bind_example.js | 53 ++++ .../nativeexample/opentsdb_json_example.js | 55 ++++ .../nativeexample/opentsdb_telnet_example.js | 38 +++ .../node/nativeexample/param_bind_example.js | 57 +++++ .../node/nativeexample/query_example.js | 17 ++ .../node/nativeexample/subscribe_demo.js | 4 + docs-examples/node/package.json | 10 + docs-examples/node/restexample/connect.js | 20 ++ docs-examples/php/connect.php | 20 ++ docs-examples/php/insert.php | 33 +++ docs-examples/php/insert_stmt.php | 49 ++++ docs-examples/php/query.php | 23 ++ docs-examples/python/.gitignore | 1 + docs-examples/python/.gitkeep | 0 docs-examples/python/async_query_example.py | 72 ++++++ docs-examples/python/bind_param_example.py | 60 +++++ docs-examples/python/conn_native_pandas.py | 19 ++ docs-examples/python/conn_rest_pandas.py | 19 ++ docs-examples/python/connect_example.py | 19 ++ .../python/connect_native_reference.py | 20 ++ docs-examples/python/connect_rest_examples.py | 45 ++++ .../connection_usage_native_reference.py | 45 ++++ .../python/cursor_usage_native_reference.py | 32 +++ docs-examples/python/handle_exception.py | 19 ++ docs-examples/python/json_protocol_example.py | 38 +++ docs-examples/python/line_protocol_example.py | 34 +++ docs-examples/python/multi_bind_example.py | 88 +++++++ docs-examples/python/native_insert_example.py | 60 +++++ docs-examples/python/query_example.py | 42 ++++ docs-examples/python/rest_client_example.py | 9 + docs-examples/python/result_set_examples.py | 33 +++ docs-examples/python/subscribe_demo.py | 38 +++ .../python/telnet_line_protocol_example.py | 38 +++ docs-examples/rust/Cargo.toml | 2 + docs-examples/rust/nativeexample/Cargo.toml | 10 + .../rust/nativeexample/examples/connect.rs | 19 ++ .../nativeexample/examples/stmt_example.rs | 38 +++ .../nativeexample/examples/subscribe_demo.rs | 3 + docs-examples/rust/nativeexample/src/main.rs | 3 + docs-examples/rust/restexample/Cargo.toml | 8 + .../rust/restexample/examples/connect.rs | 20 ++ .../restexample/examples/insert_example.rs | 18 ++ .../restexample/examples/query_example.rs | 39 +++ docs-examples/rust/restexample/src/main.rs | 3 + .../rust/schemalessexample/Cargo.toml | 7 + .../examples/influxdb_line_example.rs | 22 ++ .../examples/opentsdb_json_example.rs | 25 ++ .../examples/opentsdb_telnet_example.rs | 28 +++ .../rust/schemalessexample/src/main.rs | 3 + 116 files changed, 4454 insertions(+) create mode 100644 docs-examples/.gitignore create mode 100644 docs-examples/.gitignre create mode 100644 docs-examples/R/connect_native.r create mode 100644 docs-examples/R/connect_rest.r create mode 100644 docs-examples/c/.gitignore create mode 100644 docs-examples/c/async_query_example.c create mode 100644 docs-examples/c/connect_example.c create mode 100644 docs-examples/c/error_handle_example.c create mode 100644 docs-examples/c/insert_example.c create mode 100644 docs-examples/c/json_protocol_example.c create mode 100644 docs-examples/c/line_example.c create mode 100644 docs-examples/c/multi_bind_example.c create mode 100644 docs-examples/c/query_example.c create mode 100644 docs-examples/c/stmt_example.c create mode 100644 docs-examples/c/subscribe_demo.c create mode 100644 docs-examples/c/telnet_line_example.c create mode 100644 docs-examples/csharp/.gitignore create mode 100644 docs-examples/csharp/AsyncQueryExample.cs create mode 100644 docs-examples/csharp/ConnectExample.cs create mode 100644 docs-examples/csharp/InfluxDBLineExample.cs create mode 100644 docs-examples/csharp/OptsJsonExample.cs create mode 100644 docs-examples/csharp/OptsTelnetExample.cs create mode 100644 docs-examples/csharp/QueryExample.cs create mode 100644 docs-examples/csharp/SQLInsertExample.cs create mode 100644 docs-examples/csharp/StmtInsertExample.cs create mode 100644 docs-examples/csharp/SubscribeDemo.cs create mode 100644 docs-examples/csharp/asyncquery.csproj create mode 100644 docs-examples/csharp/connect.csproj create mode 100644 docs-examples/csharp/influxdbline.csproj create mode 100644 docs-examples/csharp/optsjson.csproj create mode 100644 docs-examples/csharp/optstelnet.csproj create mode 100644 docs-examples/csharp/query.csproj create mode 100644 docs-examples/csharp/sqlinsert.csproj create mode 100644 docs-examples/csharp/stmtinsert.csproj create mode 100644 docs-examples/csharp/subscribe.csproj create mode 100644 docs-examples/go/.gitignore create mode 100644 docs-examples/go/connect/afconn/main.go create mode 100644 docs-examples/go/connect/cgoexample/main.go create mode 100644 docs-examples/go/connect/restexample/main.go create mode 100644 docs-examples/go/connect/wrapper/main.go create mode 100644 docs-examples/go/go.mod create mode 100644 docs-examples/go/insert/json/main.go create mode 100644 docs-examples/go/insert/line/main.go create mode 100644 docs-examples/go/insert/stmt/main.go create mode 100644 docs-examples/go/insert/telnet/main.go create mode 100644 docs-examples/go/query/async/main.go create mode 100644 docs-examples/go/query/sync/main.go create mode 100644 docs-examples/go/rest/opentsdbjson/main.go create mode 100644 docs-examples/go/sub/main.go create mode 100644 docs-examples/java/.gitignore create mode 100644 docs-examples/java/pom.xml create mode 100644 docs-examples/java/src/main/java/com/taos/example/JNIConnectExample.java create mode 100644 docs-examples/java/src/main/java/com/taos/example/JSONProtocolExample.java create mode 100644 docs-examples/java/src/main/java/com/taos/example/LineProtocolExample.java create mode 100644 docs-examples/java/src/main/java/com/taos/example/RESTConnectExample.java create mode 100644 docs-examples/java/src/main/java/com/taos/example/RestInsertExample.java create mode 100644 docs-examples/java/src/main/java/com/taos/example/RestQueryExample.java create mode 100644 docs-examples/java/src/main/java/com/taos/example/StmtInsertExample.java create mode 100644 docs-examples/java/src/main/java/com/taos/example/SubscribeDemo.java create mode 100644 docs-examples/java/src/main/java/com/taos/example/TelnetLineProtocolExample.java create mode 100644 docs-examples/java/src/main/java/com/taos/example/WSConnectExample.java create mode 100644 docs-examples/java/src/test/java/com/taos/test/TestAll.java create mode 100644 docs-examples/node/.gitignore create mode 100644 docs-examples/node/nativeexample/async_query_example.js create mode 100644 docs-examples/node/nativeexample/connect.js create mode 100644 docs-examples/node/nativeexample/influxdb_line_example.js create mode 100644 docs-examples/node/nativeexample/insert_example.js create mode 100644 docs-examples/node/nativeexample/multi_bind_example.js create mode 100644 docs-examples/node/nativeexample/opentsdb_json_example.js create mode 100644 docs-examples/node/nativeexample/opentsdb_telnet_example.js create mode 100644 docs-examples/node/nativeexample/param_bind_example.js create mode 100644 docs-examples/node/nativeexample/query_example.js create mode 100644 docs-examples/node/nativeexample/subscribe_demo.js create mode 100644 docs-examples/node/package.json create mode 100644 docs-examples/node/restexample/connect.js create mode 100644 docs-examples/php/connect.php create mode 100644 docs-examples/php/insert.php create mode 100644 docs-examples/php/insert_stmt.php create mode 100644 docs-examples/php/query.php create mode 100644 docs-examples/python/.gitignore create mode 100644 docs-examples/python/.gitkeep create mode 100644 docs-examples/python/async_query_example.py create mode 100644 docs-examples/python/bind_param_example.py create mode 100644 docs-examples/python/conn_native_pandas.py create mode 100644 docs-examples/python/conn_rest_pandas.py create mode 100644 docs-examples/python/connect_example.py create mode 100644 docs-examples/python/connect_native_reference.py create mode 100644 docs-examples/python/connect_rest_examples.py create mode 100644 docs-examples/python/connection_usage_native_reference.py create mode 100644 docs-examples/python/cursor_usage_native_reference.py create mode 100644 docs-examples/python/handle_exception.py create mode 100644 docs-examples/python/json_protocol_example.py create mode 100644 docs-examples/python/line_protocol_example.py create mode 100644 docs-examples/python/multi_bind_example.py create mode 100644 docs-examples/python/native_insert_example.py create mode 100644 docs-examples/python/query_example.py create mode 100644 docs-examples/python/rest_client_example.py create mode 100644 docs-examples/python/result_set_examples.py create mode 100644 docs-examples/python/subscribe_demo.py create mode 100644 docs-examples/python/telnet_line_protocol_example.py create mode 100644 docs-examples/rust/Cargo.toml create mode 100644 docs-examples/rust/nativeexample/Cargo.toml create mode 100644 docs-examples/rust/nativeexample/examples/connect.rs create mode 100644 docs-examples/rust/nativeexample/examples/stmt_example.rs create mode 100644 docs-examples/rust/nativeexample/examples/subscribe_demo.rs create mode 100644 docs-examples/rust/nativeexample/src/main.rs create mode 100644 docs-examples/rust/restexample/Cargo.toml create mode 100644 docs-examples/rust/restexample/examples/connect.rs create mode 100644 docs-examples/rust/restexample/examples/insert_example.rs create mode 100644 docs-examples/rust/restexample/examples/query_example.rs create mode 100644 docs-examples/rust/restexample/src/main.rs create mode 100644 docs-examples/rust/schemalessexample/Cargo.toml create mode 100644 docs-examples/rust/schemalessexample/examples/influxdb_line_example.rs create mode 100644 docs-examples/rust/schemalessexample/examples/opentsdb_json_example.rs create mode 100644 docs-examples/rust/schemalessexample/examples/opentsdb_telnet_example.rs create mode 100644 docs-examples/rust/schemalessexample/src/main.rs diff --git a/docs-examples/.gitignore b/docs-examples/.gitignore new file mode 100644 index 0000000000..7ed6d403bf --- /dev/null +++ b/docs-examples/.gitignore @@ -0,0 +1,3 @@ +.vscode +*.lock +.idea \ No newline at end of file diff --git a/docs-examples/.gitignre b/docs-examples/.gitignre new file mode 100644 index 0000000000..0853156c65 --- /dev/null +++ b/docs-examples/.gitignre @@ -0,0 +1,2 @@ +.vscode +*.lock \ No newline at end of file diff --git a/docs-examples/R/connect_native.r b/docs-examples/R/connect_native.r new file mode 100644 index 0000000000..18c142872b --- /dev/null +++ b/docs-examples/R/connect_native.r @@ -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 \ No newline at end of file diff --git a/docs-examples/R/connect_rest.r b/docs-examples/R/connect_rest.r new file mode 100644 index 0000000000..5ceec572fc --- /dev/null +++ b/docs-examples/R/connect_rest.r @@ -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) \ No newline at end of file diff --git a/docs-examples/c/.gitignore b/docs-examples/c/.gitignore new file mode 100644 index 0000000000..afe9743149 --- /dev/null +++ b/docs-examples/c/.gitignore @@ -0,0 +1,3 @@ +* +!*.c +!.gitignore diff --git a/docs-examples/c/async_query_example.c b/docs-examples/c/async_query_example.c new file mode 100644 index 0000000000..262757f02b --- /dev/null +++ b/docs-examples/c/async_query_example.c @@ -0,0 +1,195 @@ +// compile with: +// gcc -o async_query_example async_query_example.c -ltaos + +#include +#include +#include +#include +#include +#include + +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 \ No newline at end of file diff --git a/docs-examples/c/connect_example.c b/docs-examples/c/connect_example.c new file mode 100644 index 0000000000..1a23df4806 --- /dev/null +++ b/docs-examples/c/connect_example.c @@ -0,0 +1,24 @@ +// compile with +// gcc connect_example.c -o connect_example -ltaos +#include +#include +#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(); +} diff --git a/docs-examples/c/error_handle_example.c b/docs-examples/c/error_handle_example.c new file mode 100644 index 0000000000..e7dedb263d --- /dev/null +++ b/docs-examples/c/error_handle_example.c @@ -0,0 +1,24 @@ +// compile with +// gcc error_handle_example.c -o error_handle_example -ltaos +#include +#include +#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(); +} diff --git a/docs-examples/c/insert_example.c b/docs-examples/c/insert_example.c new file mode 100644 index 0000000000..ca12be9314 --- /dev/null +++ b/docs-examples/c/insert_example.c @@ -0,0 +1,51 @@ +// compile with +// gcc -o insert_example insert_example.c -ltaos +#include +#include +#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 \ No newline at end of file diff --git a/docs-examples/c/json_protocol_example.c b/docs-examples/c/json_protocol_example.c new file mode 100644 index 0000000000..182fd20130 --- /dev/null +++ b/docs-examples/c/json_protocol_example.c @@ -0,0 +1,52 @@ +// compile with +// gcc -o json_protocol_example json_protocol_example.c -ltaos +#include +#include +#include +#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 diff --git a/docs-examples/c/line_example.c b/docs-examples/c/line_example.c new file mode 100644 index 0000000000..8dd4b1a507 --- /dev/null +++ b/docs-examples/c/line_example.c @@ -0,0 +1,47 @@ +// compile with +// gcc -o line_example line_example.c -ltaos +#include +#include +#include +#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 \ No newline at end of file diff --git a/docs-examples/c/multi_bind_example.c b/docs-examples/c/multi_bind_example.c new file mode 100644 index 0000000000..fe11df9caa --- /dev/null +++ b/docs-examples/c/multi_bind_example.c @@ -0,0 +1,147 @@ +// compile with +// gcc -o multi_bind_example multi_bind_example.c -ltaos +#include +#include +#include +#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 \ No newline at end of file diff --git a/docs-examples/c/query_example.c b/docs-examples/c/query_example.c new file mode 100644 index 0000000000..f88b2467ce --- /dev/null +++ b/docs-examples/c/query_example.c @@ -0,0 +1,143 @@ +// compile with: +// gcc -o query_example query_example.c -ltaos +#include +#include +#include +#include +#include + +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 \ No newline at end of file diff --git a/docs-examples/c/stmt_example.c b/docs-examples/c/stmt_example.c new file mode 100644 index 0000000000..fab1506f95 --- /dev/null +++ b/docs-examples/c/stmt_example.c @@ -0,0 +1,141 @@ +// compile with +// gcc -o stmt_example stmt_example.c -ltaos +#include +#include +#include +#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 \ No newline at end of file diff --git a/docs-examples/c/subscribe_demo.c b/docs-examples/c/subscribe_demo.c new file mode 100644 index 0000000000..2fe62c24eb --- /dev/null +++ b/docs-examples/c/subscribe_demo.c @@ -0,0 +1,66 @@ +// A simple demo for asynchronous subscription. +// compile with: +// gcc -o subscribe_demo subscribe_demo.c -ltaos + +#include +#include +#include +#include + +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(); +} diff --git a/docs-examples/c/telnet_line_example.c b/docs-examples/c/telnet_line_example.c new file mode 100644 index 0000000000..913d433f6a --- /dev/null +++ b/docs-examples/c/telnet_line_example.c @@ -0,0 +1,54 @@ +// compile with +// gcc -o telnet_line_example telnet_line_example.c -ltaos +#include +#include +#include +#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 diff --git a/docs-examples/csharp/.gitignore b/docs-examples/csharp/.gitignore new file mode 100644 index 0000000000..b3aff79f37 --- /dev/null +++ b/docs-examples/csharp/.gitignore @@ -0,0 +1,4 @@ +bin +obj +.vs +*.sln \ No newline at end of file diff --git a/docs-examples/csharp/AsyncQueryExample.cs b/docs-examples/csharp/AsyncQueryExample.cs new file mode 100644 index 0000000000..fe30d21efe --- /dev/null +++ b/docs-examples/csharp/AsyncQueryExample.cs @@ -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 metaList = TDengine.FetchFields(res); + int fieldCount = metaList.Count; + // metaList.ForEach((item) => { Console.Write("{0} ({1}) \t|\t", item.name, item.size); }); + + List 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 QueryRes(IntPtr res, List meta) + { + IntPtr taosRow; + List 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 FetchRow(IntPtr taosRow, IntPtr taosRes)//, List metaList, int numOfFiled + { + List metaList = TDengine.FetchFields(taosRes); + int numOfFiled = TDengine.FieldCount(taosRes); + + + List 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. \ No newline at end of file diff --git a/docs-examples/csharp/ConnectExample.cs b/docs-examples/csharp/ConnectExample.cs new file mode 100644 index 0000000000..f3548ee65d --- /dev/null +++ b/docs-examples/csharp/ConnectExample.cs @@ -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(); + } + } +} diff --git a/docs-examples/csharp/InfluxDBLineExample.cs b/docs-examples/csharp/InfluxDBLineExample.cs new file mode 100644 index 0000000000..7aad088252 --- /dev/null +++ b/docs-examples/csharp/InfluxDBLineExample.cs @@ -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); + } + } + +} diff --git a/docs-examples/csharp/OptsJsonExample.cs b/docs-examples/csharp/OptsJsonExample.cs new file mode 100644 index 0000000000..d774a325af --- /dev/null +++ b/docs-examples/csharp/OptsJsonExample.cs @@ -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); + } + } +} diff --git a/docs-examples/csharp/OptsTelnetExample.cs b/docs-examples/csharp/OptsTelnetExample.cs new file mode 100644 index 0000000000..81608c3221 --- /dev/null +++ b/docs-examples/csharp/OptsTelnetExample.cs @@ -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); + } + } +} diff --git a/docs-examples/csharp/QueryExample.cs b/docs-examples/csharp/QueryExample.cs new file mode 100644 index 0000000000..f00e391100 --- /dev/null +++ b/docs-examples/csharp/QueryExample.cs @@ -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 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 metaList = TDengine.FetchFields(res); + int numOfFiled = TDengine.FieldCount(res); + + List dataRaw = new List(); + + 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 \ No newline at end of file diff --git a/docs-examples/csharp/SQLInsertExample.cs b/docs-examples/csharp/SQLInsertExample.cs new file mode 100644 index 0000000000..fa2e2a50da --- /dev/null +++ b/docs-examples/csharp/SQLInsertExample.cs @@ -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 diff --git a/docs-examples/csharp/StmtInsertExample.cs b/docs-examples/csharp/StmtInsertExample.cs new file mode 100644 index 0000000000..d6e00dd4ac --- /dev/null +++ b/docs-examples/csharp/StmtInsertExample.cs @@ -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); + } + } +} diff --git a/docs-examples/csharp/SubscribeDemo.cs b/docs-examples/csharp/SubscribeDemo.cs new file mode 100644 index 0000000000..34509215da --- /dev/null +++ b/docs-examples/csharp/SubscribeDemo.cs @@ -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 + { + } +} diff --git a/docs-examples/csharp/asyncquery.csproj b/docs-examples/csharp/asyncquery.csproj new file mode 100644 index 0000000000..7a952fe7ab --- /dev/null +++ b/docs-examples/csharp/asyncquery.csproj @@ -0,0 +1,15 @@ + + + + Exe + net6.0 + enable + enable + TDengineExample.AsyncQueryExample + + + + + + + diff --git a/docs-examples/csharp/connect.csproj b/docs-examples/csharp/connect.csproj new file mode 100644 index 0000000000..27cffa30ae --- /dev/null +++ b/docs-examples/csharp/connect.csproj @@ -0,0 +1,15 @@ + + + + Exe + net6.0 + enable + enable + TDengineExample.ConnectExample + + + + + + + diff --git a/docs-examples/csharp/influxdbline.csproj b/docs-examples/csharp/influxdbline.csproj new file mode 100644 index 0000000000..a8b197dc71 --- /dev/null +++ b/docs-examples/csharp/influxdbline.csproj @@ -0,0 +1,15 @@ + + + + Exe + net6.0 + enable + enable + TDengineExample.InfluxDBLineExample + + + + + + + diff --git a/docs-examples/csharp/optsjson.csproj b/docs-examples/csharp/optsjson.csproj new file mode 100644 index 0000000000..b1bd83405e --- /dev/null +++ b/docs-examples/csharp/optsjson.csproj @@ -0,0 +1,15 @@ + + + + Exe + net6.0 + enable + enable + TDengineExample.OptsJsonExample + + + + + + + diff --git a/docs-examples/csharp/optstelnet.csproj b/docs-examples/csharp/optstelnet.csproj new file mode 100644 index 0000000000..1ab4106771 --- /dev/null +++ b/docs-examples/csharp/optstelnet.csproj @@ -0,0 +1,15 @@ + + + + Exe + net6.0 + enable + enable + TDengineExample.OptsTelnetExample + + + + + + + diff --git a/docs-examples/csharp/query.csproj b/docs-examples/csharp/query.csproj new file mode 100644 index 0000000000..63f13c3ddb --- /dev/null +++ b/docs-examples/csharp/query.csproj @@ -0,0 +1,15 @@ + + + + Exe + net6.0 + enable + enable + TDengineExample.QueryExample + + + + + + + diff --git a/docs-examples/csharp/sqlinsert.csproj b/docs-examples/csharp/sqlinsert.csproj new file mode 100644 index 0000000000..0380395a5a --- /dev/null +++ b/docs-examples/csharp/sqlinsert.csproj @@ -0,0 +1,15 @@ + + + + Exe + net6.0 + enable + enable + TDengineExample.SQLInsertExample + + + + + + + diff --git a/docs-examples/csharp/stmtinsert.csproj b/docs-examples/csharp/stmtinsert.csproj new file mode 100644 index 0000000000..8defb895eb --- /dev/null +++ b/docs-examples/csharp/stmtinsert.csproj @@ -0,0 +1,15 @@ + + + + Exe + net6.0 + enable + enable + TDengineExample.StmtInsertExample + + + + + + + diff --git a/docs-examples/csharp/subscribe.csproj b/docs-examples/csharp/subscribe.csproj new file mode 100644 index 0000000000..8286922c6f --- /dev/null +++ b/docs-examples/csharp/subscribe.csproj @@ -0,0 +1,15 @@ + + + + Exe + net6.0 + enable + enable + TDengineExample.SubscribeDemo + + + + + + + diff --git a/docs-examples/go/.gitignore b/docs-examples/go/.gitignore new file mode 100644 index 0000000000..b6128386c3 --- /dev/null +++ b/docs-examples/go/.gitignore @@ -0,0 +1,3 @@ +.idea +.vscode +tmp/ \ No newline at end of file diff --git a/docs-examples/go/connect/afconn/main.go b/docs-examples/go/connect/afconn/main.go new file mode 100644 index 0000000000..2d36ef03ab --- /dev/null +++ b/docs-examples/go/connect/afconn/main.go @@ -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") + } +} diff --git a/docs-examples/go/connect/cgoexample/main.go b/docs-examples/go/connect/cgoexample/main.go new file mode 100644 index 0000000000..8b9aba4ce4 --- /dev/null +++ b/docs-examples/go/connect/cgoexample/main.go @@ -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. diff --git a/docs-examples/go/connect/restexample/main.go b/docs-examples/go/connect/restexample/main.go new file mode 100644 index 0000000000..9c05e7eed8 --- /dev/null +++ b/docs-examples/go/connect/restexample/main.go @@ -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. diff --git a/docs-examples/go/connect/wrapper/main.go b/docs-examples/go/connect/wrapper/main.go new file mode 100644 index 0000000000..d7e71a8baf --- /dev/null +++ b/docs-examples/go/connect/wrapper/main.go @@ -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") + } +} diff --git a/docs-examples/go/go.mod b/docs-examples/go/go.mod new file mode 100644 index 0000000000..5945e395e9 --- /dev/null +++ b/docs-examples/go/go.mod @@ -0,0 +1,6 @@ +module goexample + +go 1.17 + +require github.com/taosdata/driver-go/v2 develop + diff --git a/docs-examples/go/insert/json/main.go b/docs-examples/go/insert/json/main.go new file mode 100644 index 0000000000..47d9e9984a --- /dev/null +++ b/docs-examples/go/insert/json/main.go @@ -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) + } +} diff --git a/docs-examples/go/insert/line/main.go b/docs-examples/go/insert/line/main.go new file mode 100644 index 0000000000..bbc41468fe --- /dev/null +++ b/docs-examples/go/insert/line/main.go @@ -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) + } +} diff --git a/docs-examples/go/insert/stmt/main.go b/docs-examples/go/insert/stmt/main.go new file mode 100644 index 0000000000..c50200ebb4 --- /dev/null +++ b/docs-examples/go/insert/stmt/main.go @@ -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") +} diff --git a/docs-examples/go/insert/telnet/main.go b/docs-examples/go/insert/telnet/main.go new file mode 100644 index 0000000000..879e6d5cec --- /dev/null +++ b/docs-examples/go/insert/telnet/main.go @@ -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) + } +} diff --git a/docs-examples/go/query/async/main.go b/docs-examples/go/query/async/main.go new file mode 100644 index 0000000000..7776ec8d3f --- /dev/null +++ b/docs-examples/go/query/async/main.go @@ -0,0 +1,7 @@ +package main + +import "fmt" + +func main() { + fmt.Println("hello world!") +} diff --git a/docs-examples/go/query/sync/main.go b/docs-examples/go/query/sync/main.go new file mode 100644 index 0000000000..0326c7a7da --- /dev/null +++ b/docs-examples/go/query/sync/main.go @@ -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) + } +} diff --git a/docs-examples/go/rest/opentsdbjson/main.go b/docs-examples/go/rest/opentsdbjson/main.go new file mode 100644 index 0000000000..f4f5792e29 --- /dev/null +++ b/docs-examples/go/rest/opentsdbjson/main.go @@ -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) + + } +} diff --git a/docs-examples/go/sub/main.go b/docs-examples/go/sub/main.go new file mode 100644 index 0000000000..c44521b340 --- /dev/null +++ b/docs-examples/go/sub/main.go @@ -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) + } + }() + } +} + +// 未完成 diff --git a/docs-examples/java/.gitignore b/docs-examples/java/.gitignore new file mode 100644 index 0000000000..d48c759d6c --- /dev/null +++ b/docs-examples/java/.gitignore @@ -0,0 +1,2 @@ +.idea +.vscode \ No newline at end of file diff --git a/docs-examples/java/pom.xml b/docs-examples/java/pom.xml new file mode 100644 index 0000000000..a48ba398da --- /dev/null +++ b/docs-examples/java/pom.xml @@ -0,0 +1,35 @@ + + + + 4.0.0 + + com.taos + javaexample + 1.0 + + JavaExample + + + UTF-8 + 1.8 + 1.8 + + + + + + com.taosdata.jdbc + taos-jdbcdriver + 2.0.38 + + + + junit + junit + 4.13.1 + test + + + + diff --git a/docs-examples/java/src/main/java/com/taos/example/JNIConnectExample.java b/docs-examples/java/src/main/java/com/taos/example/JNIConnectExample.java new file mode 100644 index 0000000000..c6ce2ef978 --- /dev/null +++ b/docs-examples/java/src/main/java/com/taos/example/JNIConnectExample.java @@ -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. \ No newline at end of file diff --git a/docs-examples/java/src/main/java/com/taos/example/JSONProtocolExample.java b/docs-examples/java/src/main/java/com/taos/example/JSONProtocolExample.java new file mode 100644 index 0000000000..cb83424576 --- /dev/null +++ b/docs-examples/java/src/main/java/com/taos/example/JSONProtocolExample.java @@ -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); + } + } +} diff --git a/docs-examples/java/src/main/java/com/taos/example/LineProtocolExample.java b/docs-examples/java/src/main/java/com/taos/example/LineProtocolExample.java new file mode 100644 index 0000000000..8a2eabe0a9 --- /dev/null +++ b/docs-examples/java/src/main/java/com/taos/example/LineProtocolExample.java @@ -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); + } + } +} diff --git a/docs-examples/java/src/main/java/com/taos/example/RESTConnectExample.java b/docs-examples/java/src/main/java/com/taos/example/RESTConnectExample.java new file mode 100644 index 0000000000..9d077812e0 --- /dev/null +++ b/docs-examples/java/src/main/java/com/taos/example/RESTConnectExample.java @@ -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 +} \ No newline at end of file diff --git a/docs-examples/java/src/main/java/com/taos/example/RestInsertExample.java b/docs-examples/java/src/main/java/com/taos/example/RestInsertExample.java new file mode 100644 index 0000000000..de89f26cbe --- /dev/null +++ b/docs-examples/java/src/main/java/com/taos/example/RestInsertExample.java @@ -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 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(); + } +} diff --git a/docs-examples/java/src/main/java/com/taos/example/RestQueryExample.java b/docs-examples/java/src/main/java/com/taos/example/RestQueryExample.java new file mode 100644 index 0000000000..b1a1d224c6 --- /dev/null +++ b/docs-examples/java/src/main/java/com/taos/example/RestQueryExample.java @@ -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 diff --git a/docs-examples/java/src/main/java/com/taos/example/StmtInsertExample.java b/docs-examples/java/src/main/java/com/taos/example/StmtInsertExample.java new file mode 100644 index 0000000000..2a7ccebf41 --- /dev/null +++ b/docs-examples/java/src/main/java/com/taos/example/StmtInsertExample.java @@ -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 tsToLongArray(String ts) { + ArrayList 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 ArrayList toArray(T v) { + ArrayList result = new ArrayList<>(); + result.add(v); + return result; + } + + private static List 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(); + } +} diff --git a/docs-examples/java/src/main/java/com/taos/example/SubscribeDemo.java b/docs-examples/java/src/main/java/com/taos/example/SubscribeDemo.java new file mode 100644 index 0000000000..d82d03b9de --- /dev/null +++ b/docs-examples/java/src/main/java/com/taos/example/SubscribeDemo.java @@ -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(); + } + } + } +} \ No newline at end of file diff --git a/docs-examples/java/src/main/java/com/taos/example/TelnetLineProtocolExample.java b/docs-examples/java/src/main/java/com/taos/example/TelnetLineProtocolExample.java new file mode 100644 index 0000000000..1431eccf16 --- /dev/null +++ b/docs-examples/java/src/main/java/com/taos/example/TelnetLineProtocolExample.java @@ -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: =[ =] + 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); + } + } + +} diff --git a/docs-examples/java/src/main/java/com/taos/example/WSConnectExample.java b/docs-examples/java/src/main/java/com/taos/example/WSConnectExample.java new file mode 100644 index 0000000000..48d1dde593 --- /dev/null +++ b/docs-examples/java/src/main/java/com/taos/example/WSConnectExample.java @@ -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 +} diff --git a/docs-examples/java/src/test/java/com/taos/test/TestAll.java b/docs-examples/java/src/test/java/com/taos/test/TestAll.java new file mode 100644 index 0000000000..92fe14a49d --- /dev/null +++ b/docs-examples/java/src/test/java/com/taos/test/TestAll.java @@ -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); + } +} diff --git a/docs-examples/node/.gitignore b/docs-examples/node/.gitignore new file mode 100644 index 0000000000..1071ed2b9f --- /dev/null +++ b/docs-examples/node/.gitignore @@ -0,0 +1,3 @@ +node_modules +package-lock.json +yarn-lock.json \ No newline at end of file diff --git a/docs-examples/node/nativeexample/async_query_example.js b/docs-examples/node/nativeexample/async_query_example.js new file mode 100644 index 0000000000..25b78bc48a --- /dev/null +++ b/docs-examples/node/nativeexample/async_query_example.js @@ -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 diff --git a/docs-examples/node/nativeexample/connect.js b/docs-examples/node/nativeexample/connect.js new file mode 100644 index 0000000000..da791c566e --- /dev/null +++ b/docs-examples/node/nativeexample/connect.js @@ -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 diff --git a/docs-examples/node/nativeexample/influxdb_line_example.js b/docs-examples/node/nativeexample/influxdb_line_example.js new file mode 100644 index 0000000000..a9fc6d11df --- /dev/null +++ b/docs-examples/node/nativeexample/influxdb_line_example.js @@ -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(); +} diff --git a/docs-examples/node/nativeexample/insert_example.js b/docs-examples/node/nativeexample/insert_example.js new file mode 100644 index 0000000000..85a353f889 --- /dev/null +++ b/docs-examples/node/nativeexample/insert_example.js @@ -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 diff --git a/docs-examples/node/nativeexample/multi_bind_example.js b/docs-examples/node/nativeexample/multi_bind_example.js new file mode 100644 index 0000000000..d52581ec8e --- /dev/null +++ b/docs-examples/node/nativeexample/multi_bind_example.js @@ -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(); +} diff --git a/docs-examples/node/nativeexample/opentsdb_json_example.js b/docs-examples/node/nativeexample/opentsdb_json_example.js new file mode 100644 index 0000000000..6d436a8e9e --- /dev/null +++ b/docs-examples/node/nativeexample/opentsdb_json_example.js @@ -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(); +} diff --git a/docs-examples/node/nativeexample/opentsdb_telnet_example.js b/docs-examples/node/nativeexample/opentsdb_telnet_example.js new file mode 100644 index 0000000000..01e79c2dca --- /dev/null +++ b/docs-examples/node/nativeexample/opentsdb_telnet_example.js @@ -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(); +} diff --git a/docs-examples/node/nativeexample/param_bind_example.js b/docs-examples/node/nativeexample/param_bind_example.js new file mode 100644 index 0000000000..9117f46c3e --- /dev/null +++ b/docs-examples/node/nativeexample/param_bind_example.js @@ -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(); +} diff --git a/docs-examples/node/nativeexample/query_example.js b/docs-examples/node/nativeexample/query_example.js new file mode 100644 index 0000000000..a51bc939ae --- /dev/null +++ b/docs-examples/node/nativeexample/query_example.js @@ -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 | diff --git a/docs-examples/node/nativeexample/subscribe_demo.js b/docs-examples/node/nativeexample/subscribe_demo.js new file mode 100644 index 0000000000..bdf0c98687 --- /dev/null +++ b/docs-examples/node/nativeexample/subscribe_demo.js @@ -0,0 +1,4 @@ +const taos = require("td2.0-connector"); + +const conn = taos.connect({ host: "localhost", database: "power" }); +// 未完成 \ No newline at end of file diff --git a/docs-examples/node/package.json b/docs-examples/node/package.json new file mode 100644 index 0000000000..f56196d2e5 --- /dev/null +++ b/docs-examples/node/package.json @@ -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" + } +} diff --git a/docs-examples/node/restexample/connect.js b/docs-examples/node/restexample/connect.js new file mode 100644 index 0000000000..b84ce2fadf --- /dev/null +++ b/docs-examples/node/restexample/connect.js @@ -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 | diff --git a/docs-examples/php/connect.php b/docs-examples/php/connect.php new file mode 100644 index 0000000000..5af77b9768 --- /dev/null +++ b/docs-examples/php/connect.php @@ -0,0 +1,20 @@ +connect(); +} catch (TDengineException $e) { + // 连接失败捕获异常 + throw $e; +} diff --git a/docs-examples/php/insert.php b/docs-examples/php/insert.php new file mode 100644 index 0000000000..0d9cfc4843 --- /dev/null +++ b/docs-examples/php/insert.php @@ -0,0 +1,33 @@ +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; +} diff --git a/docs-examples/php/insert_stmt.php b/docs-examples/php/insert_stmt.php new file mode 100644 index 0000000000..5d4b4809d2 --- /dev/null +++ b/docs-examples/php/insert_stmt.php @@ -0,0 +1,49 @@ +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; +} diff --git a/docs-examples/php/query.php b/docs-examples/php/query.php new file mode 100644 index 0000000000..4e86a2cec7 --- /dev/null +++ b/docs-examples/php/query.php @@ -0,0 +1,23 @@ +connect(); + + $resource = $connection->query('SELECT ts, current FROM meters LIMIT 2'); + var_dump($resource->fetch()); +} catch (TDengineException $e) { + // 捕获异常 + throw $e; +} diff --git a/docs-examples/python/.gitignore b/docs-examples/python/.gitignore new file mode 100644 index 0000000000..723ef36f4e --- /dev/null +++ b/docs-examples/python/.gitignore @@ -0,0 +1 @@ +.idea \ No newline at end of file diff --git a/docs-examples/python/.gitkeep b/docs-examples/python/.gitkeep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/docs-examples/python/async_query_example.py b/docs-examples/python/async_query_example.py new file mode 100644 index 0000000000..a78f44230a --- /dev/null +++ b/docs-examples/python/async_query_example.py @@ -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 } diff --git a/docs-examples/python/bind_param_example.py b/docs-examples/python/bind_param_example.py new file mode 100644 index 0000000000..503a2eb5dd --- /dev/null +++ b/docs-examples/python/bind_param_example.py @@ -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() diff --git a/docs-examples/python/conn_native_pandas.py b/docs-examples/python/conn_native_pandas.py new file mode 100644 index 0000000000..314759f766 --- /dev/null +++ b/docs-examples/python/conn_native_pandas.py @@ -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) +# +# 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 diff --git a/docs-examples/python/conn_rest_pandas.py b/docs-examples/python/conn_rest_pandas.py new file mode 100644 index 0000000000..143e4275fa --- /dev/null +++ b/docs-examples/python/conn_rest_pandas.py @@ -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: +# +# 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 diff --git a/docs-examples/python/connect_example.py b/docs-examples/python/connect_example.py new file mode 100644 index 0000000000..719af79fd1 --- /dev/null +++ b/docs-examples/python/connect_example.py @@ -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() diff --git a/docs-examples/python/connect_native_reference.py b/docs-examples/python/connect_native_reference.py new file mode 100644 index 0000000000..c17e9795b5 --- /dev/null +++ b/docs-examples/python/connect_native_reference.py @@ -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 diff --git a/docs-examples/python/connect_rest_examples.py b/docs-examples/python/connect_rest_examples.py new file mode 100644 index 0000000000..a043d506b9 --- /dev/null +++ b/docs-examples/python/connect_rest_examples.py @@ -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 diff --git a/docs-examples/python/connection_usage_native_reference.py b/docs-examples/python/connection_usage_native_reference.py new file mode 100644 index 0000000000..4803511e42 --- /dev/null +++ b/docs-examples/python/connection_usage_native_reference.py @@ -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() diff --git a/docs-examples/python/cursor_usage_native_reference.py b/docs-examples/python/cursor_usage_native_reference.py new file mode 100644 index 0000000000..a5103810f0 --- /dev/null +++ b/docs-examples/python/cursor_usage_native_reference.py @@ -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)] diff --git a/docs-examples/python/handle_exception.py b/docs-examples/python/handle_exception.py new file mode 100644 index 0000000000..59554465c0 --- /dev/null +++ b/docs-examples/python/handle_exception.py @@ -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' diff --git a/docs-examples/python/json_protocol_example.py b/docs-examples/python/json_protocol_example.py new file mode 100644 index 0000000000..5bb4d629bc --- /dev/null +++ b/docs-examples/python/json_protocol_example.py @@ -0,0 +1,38 @@ +import json + +import taos +from taos import SmlProtocol, SmlPrecision + +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}}] + + +def get_connection(): + return taos.connect() + + +def create_database(conn): + conn.execute("CREATE DATABASE test") + conn.execute("USE test") + + +def insert_lines(conn): + global lines + lines = json.dumps(lines) + # note: the first parameter must be a list with only one element. + affected_rows = conn.schemaless_insert( + [lines], SmlProtocol.JSON_PROTOCOL, SmlPrecision.NOT_CONFIGURED) + print(affected_rows) # 4 + + +if __name__ == '__main__': + connection = get_connection() + try: + create_database(connection) + insert_lines(connection) + finally: + connection.close() diff --git a/docs-examples/python/line_protocol_example.py b/docs-examples/python/line_protocol_example.py new file mode 100644 index 0000000000..02baeb2104 --- /dev/null +++ b/docs-examples/python/line_protocol_example.py @@ -0,0 +1,34 @@ +import taos +from taos import SmlProtocol, SmlPrecision + +lines = ["meters,location=Beijing.Haidian,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249000", + "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", + ] + + +def get_connection(): + # create connection use firstEP in taos.cfg. + return taos.connect() + + +def create_database(conn): + # the default precision is ms (microsecond), but we use us(microsecond) here. + conn.execute("CREATE DATABASE test precision 'us'") + conn.execute("USE test") + + +def insert_lines(conn): + affected_rows = conn.schemaless_insert( + lines, SmlProtocol.LINE_PROTOCOL, SmlPrecision.MICRO_SECONDS) + print(affected_rows) # 8 + + +if __name__ == '__main__': + connection = get_connection() + try: + create_database(connection) + insert_lines(connection) + finally: + connection.close() diff --git a/docs-examples/python/multi_bind_example.py b/docs-examples/python/multi_bind_example.py new file mode 100644 index 0000000000..1714121d72 --- /dev/null +++ b/docs-examples/python/multi_bind_example.py @@ -0,0 +1,88 @@ +import taos +from datetime import datetime + +# ANCHOR: bind_batch +table_tags = { + "d1001": ('Beijing.Chaoyang', 2), + "d1002": ('Beijing.Chaoyang', 3), + "d1003": ('Beijing.Haidian', 2), + "d1004": ('Beijing.Haidian', 3) +} + +table_values = { + "d1001": [ + ['2018-10-03 14:38:05.000', '2018-10-03 14:38:15.000', '2018-10-03 14:38:16.800'], + [10.3, 12.6, 12.3], + [219, 218, 221], + [0.31, 0.33, 0.32] + ], + "d1002": [ + ['2018-10-03 14:38:16.650'], [10.3], [218], [0.25] + ], + "d1003": [ + ['2018-10-03 14:38:05.500', '2018-10-03 14:38:16.600'], + [11.8, 13.4], + [221, 223], + [0.28, 0.29] + ], + "d1004": [ + ['2018-10-03 14:38:05.500', '2018-10-03 14:38:06.500'], + [10.8, 11.5], + [223, 221], + [0.29, 0.35] + ] +} + + +def bind_multi_rows(stmt: taos.TaosStmt): + """ + batch bind example + """ + for tb_name in table_values.keys(): + tags = table_tags[tb_name] + tag_params = taos.new_bind_params(2) + tag_params[0].binary(tags[0]) + tag_params[1].int(tags[1]) + stmt.set_tbname_tags(tb_name, tag_params) + + values = table_values[tb_name] + value_params = taos.new_multi_binds(4) + value_params[0].timestamp([get_ts(t) for t in values[0]]) + value_params[1].float(values[1]) + value_params[2].int(values[2]) + value_params[3].float(values[3]) + stmt.bind_param_batch(value_params) + + +def insert_data(): + conn = taos.connect(database="power") + try: + stmt = conn.statement("INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)") + bind_multi_rows(stmt) + stmt.execute() + stmt.close() + finally: + conn.close() + + +# ANCHOR_END: bind_batch + + +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 get_ts(ts: str): + dt = datetime.strptime(ts, '%Y-%m-%d %H:%M:%S.%f') + return int(dt.timestamp() * 1000) + + +if __name__ == '__main__': + create_stable() + insert_data() diff --git a/docs-examples/python/native_insert_example.py b/docs-examples/python/native_insert_example.py new file mode 100644 index 0000000000..94d4888a8f --- /dev/null +++ b/docs-examples/python/native_insert_example.py @@ -0,0 +1,60 @@ +import taos + +lines = ["d1001,2018-10-03 14:38:05.000,10.30000,219,0.31000,Beijing.Chaoyang,2", + "d1004,2018-10-03 14:38:05.000,10.80000,223,0.29000,Beijing.Haidian,3", + "d1003,2018-10-03 14:38:05.500,11.80000,221,0.28000,Beijing.Haidian,2", + "d1004,2018-10-03 14:38:06.500,11.50000,221,0.35000,Beijing.Haidian,3", + "d1002,2018-10-03 14:38:16.650,10.30000,218,0.25000,Beijing.Chaoyang,3", + "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", + "d1003,2018-10-03 14:38:16.600,13.40000,223,0.29000,Beijing.Haidian,2"] + + +def get_connection() -> taos.TaosConnection: + """ + create connection use firstEp in taos.cfg and use default user and password. + """ + return taos.connect() + + +def create_stable(conn: taos.TaosConnection): + conn.execute("CREATE DATABASE power") + conn.execute("USE power") + conn.execute("CREATE STABLE meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) " + "TAGS (location BINARY(64), groupId INT)") + + +# The generated SQL is: +# 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) + +def get_sql(): + global lines + lines = map(lambda line: line.split(','), lines) # [['d1001', ...]...] + lines = sorted(lines, key=lambda ls: ls[0]) # sort by table name + sql = "INSERT INTO " + tb_name = None + for ps in lines: + tmp_tb_name = ps[0] + if tb_name != tmp_tb_name: + tb_name = tmp_tb_name + sql += f"{tb_name} USING meters TAGS({ps[5]}, {ps[6]}) VALUES " + sql += f"('{ps[1]}', {ps[2]}, {ps[3]}, {ps[4]}) " + return sql + + +def insert_data(conn: taos.TaosConnection): + sql = get_sql() + affected_rows = conn.execute(sql) + print("affected_rows", affected_rows) # 8 + + +if __name__ == '__main__': + connection = get_connection() + try: + create_stable(connection) + insert_data(connection) + finally: + connection.close() diff --git a/docs-examples/python/query_example.py b/docs-examples/python/query_example.py new file mode 100644 index 0000000000..6d33c49c96 --- /dev/null +++ b/docs-examples/python/query_example.py @@ -0,0 +1,42 @@ +import taos + + +# ANCHOR: iter +def query_api_demo(conn: taos.TaosConnection): + result: taos.TaosResult = conn.query("SELECT tbname, * FROM meters LIMIT 2") + print("field count:", result.field_count) + print("meta of fields[1]:", result.fields[1]) + print("======================Iterate on result=========================") + for row in result: + print(row) + + +# field count: 7 +# meta of files[1]: {name: ts, type: 9, bytes: 8} +# ======================Iterate on result========================= +# ('d1001', datetime.datetime(2018, 10, 3, 14, 38, 5), 10.300000190734863, 219, 0.3100000023841858, 'Beijing.Chaoyang', 2) +# ('d1001', datetime.datetime(2018, 10, 3, 14, 38, 15), 12.600000381469727, 218, 0.33000001311302185, 'Beijing.Chaoyang', 2) +# ANCHOR_END: iter + +# ANCHOR: fetch_all +def fetch_all_demo(conn: taos.TaosConnection): + result: taos.TaosResult = conn.query("SELECT ts, current FROM meters LIMIT 2") + rows = result.fetch_all_into_dict() + print("row count:", result.row_count) + print("===============all data===================") + print(rows) + + +# row count: 2 +# ===============all data=================== +# [{'ts': datetime.datetime(2018, 10, 3, 14, 38, 5), 'current': 10.300000190734863}, +# {'ts': datetime.datetime(2018, 10, 3, 14, 38, 15), 'current': 12.600000381469727}] +# ANCHOR_END: fetch_all + +if __name__ == '__main__': + connection = taos.connect(database="power") + try: + query_api_demo(connection) + fetch_all_demo(connection) + finally: + connection.close() diff --git a/docs-examples/python/rest_client_example.py b/docs-examples/python/rest_client_example.py new file mode 100644 index 0000000000..46d33a1d79 --- /dev/null +++ b/docs-examples/python/rest_client_example.py @@ -0,0 +1,9 @@ +from taosrest import RestClient + +client = RestClient("localhost", 6041, "root", "taosdata") +res: dict = client.sql("SELECT ts, current FROM power.meters LIMIT 1") +print(res) + +# output: +# {'status': 'succ', 'head': ['ts', 'current'], 'column_meta': [['ts', 9, 8], ['current', 6, 4]], 'data': [[datetime.datetime(2018, 10, 3, 14, 38, 5, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800), '+08:00')), 10.3]], 'rows': 1} + diff --git a/docs-examples/python/result_set_examples.py b/docs-examples/python/result_set_examples.py new file mode 100644 index 0000000000..6cba0d3f73 --- /dev/null +++ b/docs-examples/python/result_set_examples.py @@ -0,0 +1,33 @@ +import taos + +conn = taos.connect() +conn.execute("DROP DATABASE IF EXISTS test") +conn.execute("CREATE DATABASE test") +conn.select_db("test") +conn.execute("CREATE STABLE weather(ts TIMESTAMP, temperature FLOAT) TAGS (location INT)") +# prepare data +for i in range(2000): + location = str(i % 10) + tb = "t" + location + conn.execute(f"INSERT INTO {tb} USING weather TAGS({location}) VALUES (now+{i}a, 23.5) (now+{i + 1}a, 23.5)") + +result: taos.TaosResult = conn.query("SELECT * FROM weather") + +block_index = 0 +blocks: taos.TaosBlocks = result.blocks_iter() +for rows, length in blocks: + print("block ", block_index, " length", length) + print("first row in this block:", rows[0]) + block_index += 1 + +conn.close() + +# possible output: +# block 0 length 1200 +# first row in this block: (datetime.datetime(2022, 4, 27, 15, 14, 52, 46000), 23.5, 0) +# block 1 length 1200 +# first row in this block: (datetime.datetime(2022, 4, 27, 15, 14, 52, 76000), 23.5, 3) +# block 2 length 1200 +# first row in this block: (datetime.datetime(2022, 4, 27, 15, 14, 52, 99000), 23.5, 6) +# block 3 length 400 +# first row in this block: (datetime.datetime(2022, 4, 27, 15, 14, 52, 122000), 23.5, 9) diff --git a/docs-examples/python/subscribe_demo.py b/docs-examples/python/subscribe_demo.py new file mode 100644 index 0000000000..db9d49c3f4 --- /dev/null +++ b/docs-examples/python/subscribe_demo.py @@ -0,0 +1,38 @@ +""" +Python asynchronous subscribe demo. +run on Linux system with: python3 subscribe_demo.py +""" + +from ctypes import c_void_p + +import taos +import time + + +def query_callback(p_sub, p_result, p_param, code): + """ + :param p_sub: pointer returned by native API -- taos_subscribe + :param p_result: pointer to native TAOS_RES + :param p_param: None + :param code: error code + :return: None + """ + print("in callback") + result = taos.TaosResult(c_void_p(p_result)) + # raise exception if error occur + result.check_error(code) + for row in result.rows_iter(): + print(row) + print(f"{result.row_count} rows consumed.") + + +if __name__ == '__main__': + conn = taos.connect() + restart = True + topic = "topic-meter-current-bg" + sql = "select * from power.meters where current > 10" # Error sql + interval = 2000 # consumption interval in microseconds. + _ = conn.subscribe(restart, topic, sql, interval, query_callback) + # Note: we received the return value as _ above, to avoid the TaosSubscription object to be deleted by gc. + while True: + time.sleep(10) # use Ctrl + C to interrupt diff --git a/docs-examples/python/telnet_line_protocol_example.py b/docs-examples/python/telnet_line_protocol_example.py new file mode 100644 index 0000000000..072835109e --- /dev/null +++ b/docs-examples/python/telnet_line_protocol_example.py @@ -0,0 +1,38 @@ +import taos +from taos import SmlProtocol, SmlPrecision + +# format: =[ =] +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", + ] + + +# create connection use firstEp in taos.cfg. +def get_connection(): + return taos.connect() + + +def create_database(conn): + conn.execute("CREATE DATABASE test") + conn.execute("USE test") + + +def insert_lines(conn): + affected_rows = conn.schemaless_insert( + lines, SmlProtocol.TELNET_PROTOCOL, SmlPrecision.NOT_CONFIGURED) + print(affected_rows) # 8 + + +if __name__ == '__main__': + connection = get_connection() + try: + create_database(connection) + insert_lines(connection) + finally: + connection.close() diff --git a/docs-examples/rust/Cargo.toml b/docs-examples/rust/Cargo.toml new file mode 100644 index 0000000000..114407e69e --- /dev/null +++ b/docs-examples/rust/Cargo.toml @@ -0,0 +1,2 @@ +[workspace] +members = ["restexample", "nativeexample", "schemalessexample"] diff --git a/docs-examples/rust/nativeexample/Cargo.toml b/docs-examples/rust/nativeexample/Cargo.toml new file mode 100644 index 0000000000..64fd10a3e9 --- /dev/null +++ b/docs-examples/rust/nativeexample/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "nativeexample" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[dependencies] +libtaos = { version = "0.4.3" } +tokio = { version = "*", features = ["rt", "macros", "rt-multi-thread"] } +bstr = { version = "*" } diff --git a/docs-examples/rust/nativeexample/examples/connect.rs b/docs-examples/rust/nativeexample/examples/connect.rs new file mode 100644 index 0000000000..8e27458de5 --- /dev/null +++ b/docs-examples/rust/nativeexample/examples/connect.rs @@ -0,0 +1,19 @@ +use libtaos::*; + +fn taos_connect() -> Result { + TaosCfgBuilder::default() + .ip("localhost") + .user("root") + .pass("taosdata") + // .db("log") // remove comment if you want to connect to database log by default. + .port(6030u16) + .build() + .expect("TaosCfg builder error") + .connect() +} + +fn main() { + #[allow(unused_variables)] + let taos = taos_connect().unwrap(); + println!("Connected") +} diff --git a/docs-examples/rust/nativeexample/examples/stmt_example.rs b/docs-examples/rust/nativeexample/examples/stmt_example.rs new file mode 100644 index 0000000000..a791a41359 --- /dev/null +++ b/docs-examples/rust/nativeexample/examples/stmt_example.rs @@ -0,0 +1,38 @@ +use bstr::BString; +use libtaos::*; + +#[tokio::main] +async fn main() -> Result<(), Error> { + let taos = TaosCfg::default().connect().expect("fail to connect"); + taos.create_database("power").await?; + taos.use_database("power").await?; + taos.exec("CREATE STABLE meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)").await?; + let mut stmt = taos.stmt("INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)")?; + // bind table name and tags + stmt.set_tbname_tags( + "d1001", + [ + Field::Binary(BString::from("Beijing.Chaoyang")), + Field::Int(2), + ], + )?; + // bind values. + let values = vec![ + Field::Timestamp(Timestamp::new(1648432611249, TimestampPrecision::Milli)), + Field::Float(10.3), + Field::Int(219), + Field::Float(0.31), + ]; + stmt.bind(&values)?; + // bind one more row + let values2 = vec![ + Field::Timestamp(Timestamp::new(1648432611749, TimestampPrecision::Milli)), + Field::Float(12.6), + Field::Int(218), + Field::Float(0.33), + ]; + stmt.bind(&values2)?; + // execute + stmt.execute()?; + Ok(()) +} diff --git a/docs-examples/rust/nativeexample/examples/subscribe_demo.rs b/docs-examples/rust/nativeexample/examples/subscribe_demo.rs new file mode 100644 index 0000000000..4febff9be7 --- /dev/null +++ b/docs-examples/rust/nativeexample/examples/subscribe_demo.rs @@ -0,0 +1,3 @@ +fn main() { + +} \ No newline at end of file diff --git a/docs-examples/rust/nativeexample/src/main.rs b/docs-examples/rust/nativeexample/src/main.rs new file mode 100644 index 0000000000..e7a11a969c --- /dev/null +++ b/docs-examples/rust/nativeexample/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +} diff --git a/docs-examples/rust/restexample/Cargo.toml b/docs-examples/rust/restexample/Cargo.toml new file mode 100644 index 0000000000..a5f89f8a3b --- /dev/null +++ b/docs-examples/rust/restexample/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "restexample" +version = "0.1.0" +edition = "2021" + +[dependencies] +libtaos = { version = "0.4.3", features = ["rest"] } +tokio = { version = "*", features = ["rt", "macros", "rt-multi-thread"] } diff --git a/docs-examples/rust/restexample/examples/connect.rs b/docs-examples/rust/restexample/examples/connect.rs new file mode 100644 index 0000000000..b3718342c4 --- /dev/null +++ b/docs-examples/rust/restexample/examples/connect.rs @@ -0,0 +1,20 @@ +use libtaos::*; + +fn taos_connect() -> Result { + TaosCfgBuilder::default() + .ip("localhost") + .user("root") + .pass("taosdata") + // .db("log") // remove comment if you want to connect to database log by default. + .port(6030u16) + .build() + .expect("TaosCfg builder error") + .connect() +} + +#[tokio::main] +async fn main() { + #[allow(unused_variables)] + let taos = taos_connect().expect("connect error"); + println!("Connected") +} diff --git a/docs-examples/rust/restexample/examples/insert_example.rs b/docs-examples/rust/restexample/examples/insert_example.rs new file mode 100644 index 0000000000..d7acc98d09 --- /dev/null +++ b/docs-examples/rust/restexample/examples/insert_example.rs @@ -0,0 +1,18 @@ +use libtaos::*; + +#[tokio::main] +async fn main() -> Result<(), Error> { + let taos = TaosCfg::default().connect().expect("fail to connect"); + taos.create_database("power").await?; + taos.exec("CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)").await?; + let 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)"; + let result = taos.query(sql).await?; + println!("{:?}", result); + Ok(()) +} + +// output: +// TaosQueryData { column_meta: [ColumnMeta { name: "affected_rows", type_: Int, bytes: 4 }], rows: [[Int(8)]] } diff --git a/docs-examples/rust/restexample/examples/query_example.rs b/docs-examples/rust/restexample/examples/query_example.rs new file mode 100644 index 0000000000..bbe0cfaabf --- /dev/null +++ b/docs-examples/rust/restexample/examples/query_example.rs @@ -0,0 +1,39 @@ +use libtaos::*; + +fn taos_connect() -> Result { + TaosCfgBuilder::default() + .ip("localhost") + .user("root") + .pass("taosdata") + .db("power") + .port(6030u16) + .build() + .expect("TaosCfg builder error") + .connect() +} + +#[tokio::main] +async fn main() -> Result<(), Error> { + let taos = taos_connect().expect("connect error"); + let result = taos.query("SELECT ts, current FROM meters LIMIT 2").await?; + // print column names + let meta: Vec = result.column_meta; + for column in meta { + print!("{}\t", column.name) + } + println!(); + // print rows + let rows: Vec> = result.rows; + for row in rows { + for field in row { + print!("{}\t", field); + } + println!(); + } + Ok(()) +} + +// output: +// ts current +// 2022-03-28 09:56:51.249 10.3 +// 2022-03-28 09:56:51.749 12.6 diff --git a/docs-examples/rust/restexample/src/main.rs b/docs-examples/rust/restexample/src/main.rs new file mode 100644 index 0000000000..e7a11a969c --- /dev/null +++ b/docs-examples/rust/restexample/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +} diff --git a/docs-examples/rust/schemalessexample/Cargo.toml b/docs-examples/rust/schemalessexample/Cargo.toml new file mode 100644 index 0000000000..32c6a12231 --- /dev/null +++ b/docs-examples/rust/schemalessexample/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "schemalessexample" +version = "0.1.0" +edition = "2021" + +[dependencies] +libtaos = { version = "0.4.3" } diff --git a/docs-examples/rust/schemalessexample/examples/influxdb_line_example.rs b/docs-examples/rust/schemalessexample/examples/influxdb_line_example.rs new file mode 100644 index 0000000000..e93888cc83 --- /dev/null +++ b/docs-examples/rust/schemalessexample/examples/influxdb_line_example.rs @@ -0,0 +1,22 @@ +use libtaos::schemaless::*; +use libtaos::*; + +fn main() { + let taos = TaosCfg::default().connect().expect("fail to connect"); + taos.raw_query("CREATE DATABASE test").unwrap(); + taos.raw_query("USE test").unwrap(); + let 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"]; + let affected_rows = taos + .schemaless_insert( + &lines, + TSDB_SML_LINE_PROTOCOL, + TSDB_SML_TIMESTAMP_MILLISECONDS, + ) + .unwrap(); + println!("affected_rows={}", affected_rows); +} + +// run with: cargo run --example influxdb_line_example diff --git a/docs-examples/rust/schemalessexample/examples/opentsdb_json_example.rs b/docs-examples/rust/schemalessexample/examples/opentsdb_json_example.rs new file mode 100644 index 0000000000..1d66bd1f2b --- /dev/null +++ b/docs-examples/rust/schemalessexample/examples/opentsdb_json_example.rs @@ -0,0 +1,25 @@ +use libtaos::schemaless::*; +use libtaos::*; + +fn main() { + let taos = TaosCfg::default().connect().expect("fail to connect"); + taos.raw_query("CREATE DATABASE test").unwrap(); + taos.raw_query("USE test").unwrap(); + let lines = [ + r#"[{"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}}]"#, + ]; + + let affected_rows = taos + .schemaless_insert( + &lines, + TSDB_SML_JSON_PROTOCOL, + TSDB_SML_TIMESTAMP_NOT_CONFIGURED, + ) + .unwrap(); + println!("affected_rows={}", affected_rows); // affected_rows=4 +} + +// run with: cargo run --example opentsdb_json_example diff --git a/docs-examples/rust/schemalessexample/examples/opentsdb_telnet_example.rs b/docs-examples/rust/schemalessexample/examples/opentsdb_telnet_example.rs new file mode 100644 index 0000000000..18d7500714 --- /dev/null +++ b/docs-examples/rust/schemalessexample/examples/opentsdb_telnet_example.rs @@ -0,0 +1,28 @@ +use libtaos::schemaless::*; +use libtaos::*; + +fn main() { + let taos = TaosCfg::default().connect().expect("fail to connect"); + taos.raw_query("CREATE DATABASE test").unwrap(); + taos.raw_query("USE test").unwrap(); + let 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", + ]; + let affected_rows = taos + .schemaless_insert( + &lines, + TSDB_SML_TELNET_PROTOCOL, + TSDB_SML_TIMESTAMP_NOT_CONFIGURED, + ) + .unwrap(); + println!("affected_rows={}", affected_rows); // affected_rows=8 +} + +// run with: cargo run --example opentsdb_telnet_example diff --git a/docs-examples/rust/schemalessexample/src/main.rs b/docs-examples/rust/schemalessexample/src/main.rs new file mode 100644 index 0000000000..e7a11a969c --- /dev/null +++ b/docs-examples/rust/schemalessexample/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +}