diff --git a/docs/en/05-develop/01-connect/01-python.md b/docs/en/05-develop/01-connect/01-python.md index f01407a3c4ead99fa915ff468268e35157fec8be..c4605fce224d4e39a5f9451520e34a7317e09436 100644 --- a/docs/en/05-develop/01-connect/01-python.md +++ b/docs/en/05-develop/01-connect/01-python.md @@ -1,6 +1,7 @@ --- sidebar_label: Python title: Connect with Python Connector +pagination_next: develop/insert-data --- import Tabs from '@theme/Tabs'; @@ -30,14 +31,37 @@ conda install -c conda-forge taospy ## Config -Run this command in your terminal to save TDengine cloud token as variables: +Run this command in your terminal to save TDengine cloud token and URL as variables: + + + ```bash export TDENGINE_CLOUD_TOKEN= export TDENGINE_CLOUD_URL= ``` -Alternatively, set environment variables in your IDE's run configurations. + + + +```bash +set TDENGINE_CLOUD_TOKEN="" +set TDENGINE_CLOUD_URL="" +``` + + + + +```powershell +$env:TDENGINE_CLOUD_TOKEN="" +$env:TDENGINE_CLOUD_URL="" +``` + + + + + +Alternatively, you can also set environment variables in your IDE's run configurations. @@ -50,16 +74,10 @@ To obtain the value of cloud token and URL, please log in [TDengine Cloud](https ## Connect -Copy code bellow to your editor and run it with `python3` command. +Copy code bellow to your editor and run it. ```python -import taosrest -import os - -token = os.environ["TDENGINE_CLOUD_TOKEN"] -url = os.environ["TDENGINE_ClOUD_URL"] - -conn = taosrest.connect(url=url, token=token) +{{#include docs/examples/python/connect_cloud_example.py:connect}} ``` The client connection is then established. For how to write data and query data, please refer to [sample-program](https://docs.tdengine.com/cloud/connector/python/#sample-program). diff --git a/docs/en/05-develop/01-connect/02-java.md b/docs/en/05-develop/01-connect/02-java.md index 9cddca3aedee377b6cfe75bb9292a4522c5649ca..880ab49ec69671ad5fbce9b33a51846dab53a458 100644 --- a/docs/en/05-develop/01-connect/02-java.md +++ b/docs/en/05-develop/01-connect/02-java.md @@ -1,6 +1,7 @@ --- sidebar_label: Java title: Connect with Java Connector +pagination_next: develop/insert-data --- import Tabs from '@theme/Tabs'; @@ -36,11 +37,31 @@ dependencies { Run this command in your terminal to save the JDBC URL as variable: + + + + ```bash export TDENGINE_JDBC_URL= ``` + + + +```bash +set TDENGINE_JDBC_URL="" +``` + + + +```powershell +$env:TDENGINE_JDBC_URL="" +``` + + + + -Alternatively, set environment variable in your IDE's run configurations. +Alternatively, you can set environment variable in your IDE's run configurations. diff --git a/docs/en/05-develop/01-connect/03-go.md b/docs/en/05-develop/01-connect/03-go.md index 5b5519a8b72013aaeebf0b0f0bffc2e807ea9c98..313ae2aedcc951ecf573e455830a398e80fb1684 100644 --- a/docs/en/05-develop/01-connect/03-go.md +++ b/docs/en/05-develop/01-connect/03-go.md @@ -1,8 +1,18 @@ --- sidebar_label: Go title: Connect with Go Connector +pagination_next: develop/insert-data --- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +## Initialize Project + +``` +go mod init tdengine.com/example +``` + ## Add Dependency add `driver-go` dependency in `go.mod` . @@ -15,16 +25,35 @@ go 1.17 require github.com/taosdata/driver-go/v2 develop ``` -Then run command `go mod tidy` in your terminal to download dependencies. - ## Config Run this command in your terminal to save DSN(data source name) as variable: + + + ```bash export TDENGINE_GO_DSN= ``` + + + +```bash +set TDENGINE_GO_DSN="" +``` + + + + +```powershell +$env:TDENGINE_GO_DSN="" +``` + + + + + :::note Replace with the real value, the format should be `https()/?token=`. @@ -35,25 +64,10 @@ To obtain the value of `goDSN`, please log in [TDengine Cloud](https://cloud.tde ## Connect -```go -package main - -import ( - "database/sql" - "fmt" - "os" - - _ "github.com/taosdata/driver-go/v2/taosRestful" -) - -func main() { - dsn := os.Getenv("TDENGINE_GO_DSN") - taos, err := sql.Open("taosRestful", dsn) - if err != nil { - fmt.Println("failed to connect TDengine, err:", err) - return - } - fmt.Println("Connected") - defer taos.Close() -} -``` \ No newline at end of file +Copy code bellow to main.go. + +```go title="main.go" +{{#include docs/examples/go/connectexample/main.go}} +``` + +Then execute `go run main.go` to test the connection. \ No newline at end of file diff --git a/docs/en/05-develop/01-connect/04-rust.md b/docs/en/05-develop/01-connect/04-rust.md index aa494592ce743341928285f0368d450199871115..e03a5beb58325a1defb18936e937712728c693f5 100644 --- a/docs/en/05-develop/01-connect/04-rust.md +++ b/docs/en/05-develop/01-connect/04-rust.md @@ -1,6 +1,7 @@ --- sidebar_label: Rust title: Connect with Rust Connector +pagination_next: develop/insert-data --- ## Add Dependency diff --git a/docs/en/05-develop/01-connect/05-node.md b/docs/en/05-develop/01-connect/05-node.md index bb9ebf9a3524dfd1889319d951aa12a59672354c..8475e50cecfcaeeea556d68d6612e0c83042d2bb 100644 --- a/docs/en/05-develop/01-connect/05-node.md +++ b/docs/en/05-develop/01-connect/05-node.md @@ -1,6 +1,7 @@ --- sidebar_label: Node.js title: Connect with Node.js Connector +pagination_next: develop/insert-data --- ## Install Connector diff --git a/docs/en/05-develop/02-model.md b/docs/en/05-develop/02-model.md deleted file mode 100644 index c2b8b119d76ba8300d89d76772616d18b92bc879..0000000000000000000000000000000000000000 --- a/docs/en/05-develop/02-model.md +++ /dev/null @@ -1 +0,0 @@ -# Data Model \ No newline at end of file diff --git a/docs/en/06-taos-sql/index.md b/docs/en/06-taos-sql/index.md deleted file mode 100644 index 33656338a7bba38dc55cf536bdba8e95309c5acf..0000000000000000000000000000000000000000 --- a/docs/en/06-taos-sql/index.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: TDengine SQL -description: "The syntax supported by TDengine SQL " ---- - -This section explains the syntax of SQL to perform operations on databases, tables and STables, insert data, select data and use functions. We also provide some tips that can be used in TDengine SQL. If you have previous experience with SQL this section will be fairly easy to understand. If you do not have previous experience with SQL, you'll come to appreciate the simplicity and power of SQL. - -TDengine SQL is the major interface for users to write data into or query from TDengine. For ease of use, the syntax is similar to that of standard SQL. However, please note that TDengine SQL is not standard SQL. For instance, TDengine doesn't provide a delete function for time series data and so corresponding statements are not provided in TDengine SQL. - -Syntax Specifications used in this chapter: - -- The content inside <\> needs to be input by the user, excluding <\> itself. -- \[ \] means optional input, excluding [] itself. -- | means one of a few options, excluding | itself. -- … means the item prior to it can be repeated multiple times. - -To better demonstrate the syntax, usage and rules of TAOS SQL, hereinafter it's assumed that there is a data set of data from electric meters. Each meter collects 3 data measurements: current, voltage, phase. The data model is shown below: - -```sql -taos> DESCRIBE meters; - Field | Type | Length | Note | -================================================================================= - ts | TIMESTAMP | 8 | | - current | FLOAT | 4 | | - voltage | INT | 4 | | - phase | FLOAT | 4 | | - location | BINARY | 64 | TAG | - groupid | INT | 4 | TAG | -``` - -The data set includes the data collected by 4 meters, the corresponding table name is d1001, d1002, d1003 and d1004 based on the data model of TDengine. diff --git a/docs/en/07-tools/01-cli.md b/docs/en/07-tools/01-cli.md index 002d91eb015a14056dd4236e3d524cd18c04e1e2..867a6bd76ee440273445d7e966f77e243b99394b 100644 --- a/docs/en/07-tools/01-cli.md +++ b/docs/en/07-tools/01-cli.md @@ -13,7 +13,7 @@ The TDengine command-line interface (hereafter referred to as `TDengine CLI`) is To run TDengine CLI to access TDengine cloud, please install [TDengine client installation package](https://www.taosdata.com/assets-download/TDengine-client-2.6.0.2-Linux-x64.tar.gz) first. - + Run this command in your Linux terminal to save your URL and token as variables: @@ -34,7 +34,7 @@ set TDENGINE_CLOUD_TOKEN= ``` - + Run this command in your Mac terminal to save your URL and token as variables: @@ -46,7 +46,7 @@ export TDENGINE_CLOUD_TOKEN= - + To access the TDengine Cloud, you can execute below command from a Linux terminal. diff --git a/docs/examples/.gitignore b/docs/examples/.gitignore index 7ed6d403bf5f64c0cb230265b4dffee609dea93b..b50ab6c63b6a8968ba92af7d04edb446ec3d2776 100644 --- a/docs/examples/.gitignore +++ b/docs/examples/.gitignore @@ -1,3 +1,4 @@ .vscode *.lock -.idea \ No newline at end of file +.idea +.env \ No newline at end of file diff --git a/docs/examples/.gitignre b/docs/examples/.gitignre deleted file mode 100644 index 0853156c65c2c6c1b693290e74c3ee630bcaac19..0000000000000000000000000000000000000000 --- a/docs/examples/.gitignre +++ /dev/null @@ -1,2 +0,0 @@ -.vscode -*.lock \ No newline at end of file diff --git a/docs/examples/R/connect_native.r b/docs/examples/R/connect_native.r deleted file mode 100644 index 18c142872be5efaa7167c10a25f62bcb9fbf5a52..0000000000000000000000000000000000000000 --- a/docs/examples/R/connect_native.r +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 5ceec572fc26575dfc597983eeac3233bc4488ab..0000000000000000000000000000000000000000 --- a/docs/examples/R/connect_rest.r +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index afe974314989a1e3aa4eee703738a9a960c18577..0000000000000000000000000000000000000000 --- a/docs/examples/c/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -* -!*.c -!.gitignore diff --git a/docs/examples/c/async_query_example.c b/docs/examples/c/async_query_example.c deleted file mode 100644 index b370420b124a21b05f8e0b4041fb1461b1e2478a..0000000000000000000000000000000000000000 --- a/docs/examples/c/async_query_example.c +++ /dev/null @@ -1,195 +0,0 @@ -// 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 -// 1538548685500 11.800000 221 0.280000 california.losangeles 2 -// 1538548696600 13.400000 223 0.290000 california.losangeles 2 -// 1538548685000 10.800000 223 0.290000 california.losangeles 3 -// 1538548686500 11.500000 221 0.350000 california.losangeles 3 -// 1538548685000 10.300000 219 0.310000 california.sanfrancisco 2 -// 1538548695000 12.600000 218 0.330000 california.sanfrancisco 2 -// 1538548696800 12.300000 221 0.310000 california.sanfrancisco 2 -// 1538548696650 10.300000 218 0.250000 california.sanfrancisco 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 deleted file mode 100644 index 1a23df4806d7ff986898734e1971f6e0cd7c5360..0000000000000000000000000000000000000000 --- a/docs/examples/c/connect_example.c +++ /dev/null @@ -1,24 +0,0 @@ -// 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 deleted file mode 100644 index e7dedb263df250f6634aa15fab2729cbaf4e5972..0000000000000000000000000000000000000000 --- a/docs/examples/c/error_handle_example.c +++ /dev/null @@ -1,24 +0,0 @@ -// 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 deleted file mode 100644 index ce8fdc5b9372aec7b02d3c9254ec25c4c4f62adc..0000000000000000000000000000000000000000 --- a/docs/examples/c/insert_example.c +++ /dev/null @@ -1,51 +0,0 @@ -// 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(California.SanFrancisco, 2) VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000) ('2018-10-03 14:38:15.000', 12.60000, 218, 0.33000) ('2018-10-03 14:38:16.800', 12.30000, 221, 0.31000)" - "d1002 USING meters TAGS(California.SanFrancisco, 3) VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000)" - "d1003 USING meters TAGS(California.LosAngeles, 2) VALUES ('2018-10-03 14:38:05.500', 11.80000, 221, 0.28000) ('2018-10-03 14:38:16.600', 13.40000, 223, 0.29000)" - "d1004 USING meters TAGS(California.LosAngeles, 3) VALUES ('2018-10-03 14:38:05.000', 10.80000, 223, 0.29000) ('2018-10-03 14:38:06.500', 11.50000, 221, 0.35000)"); - 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 deleted file mode 100644 index 9d276127a64c3d74322e30587ab2e319c29cbf65..0000000000000000000000000000000000000000 --- a/docs/examples/c/json_protocol_example.c +++ /dev/null @@ -1,52 +0,0 @@ -// 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\": " - "\"California.SanFrancisco\", \"groupid\": 2}},{\"metric\": \"meters.voltage\", \"timestamp\": 1648432611249, " - "\"value\": 219, \"tags\": {\"location\": \"California.LosAngeles\", \"groupid\": 1}},{\"metric\": \"meters.current\", " - "\"timestamp\": 1648432611250, \"value\": 12.6, \"tags\": {\"location\": \"California.SanFrancisco\", \"groupid\": " - "2}},{\"metric\": \"meters.voltage\", \"timestamp\": 1648432611250, \"value\": 221, \"tags\": {\"location\": " - "\"California.LosAngeles\", \"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 deleted file mode 100644 index ce39f8d9df744082a450ce246529bf56adebd1e0..0000000000000000000000000000000000000000 --- a/docs/examples/c/line_example.c +++ /dev/null @@ -1,47 +0,0 @@ -// 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=California.LosAngeles,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249", - "meters,location=California.LosAngeles,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611250", - "meters,location=California.LosAngeles,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249", - "meters,location=California.LosAngeles,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 deleted file mode 100644 index 02e6568e9e88ac8703a4993ed406e770d23c2438..0000000000000000000000000000000000000000 --- a/docs/examples/c/multi_bind_example.c +++ /dev/null @@ -1,147 +0,0 @@ -// 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 = "California.SanFrancisco"; - 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 deleted file mode 100644 index fcae95bcd45a282eaa3ae911b4115e6300c6af8e..0000000000000000000000000000000000000000 --- a/docs/examples/c/query_example.c +++ /dev/null @@ -1,143 +0,0 @@ -// 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 California.SanFrancisco 2 -// 1648432611749 12.600000 218 0.330000 California.SanFrancisco 2 \ No newline at end of file diff --git a/docs/examples/c/stmt_example.c b/docs/examples/c/stmt_example.c deleted file mode 100644 index 28dae5f9d5ea2faec0aa3c0a784d39e252651c65..0000000000000000000000000000000000000000 --- a/docs/examples/c/stmt_example.c +++ /dev/null @@ -1,141 +0,0 @@ -// 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 = "California.SanFrancisco"; - 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 deleted file mode 100644 index 2fe62c24eb92d2f57c24b40fc16f47d62ea5e378..0000000000000000000000000000000000000000 --- a/docs/examples/c/subscribe_demo.c +++ /dev/null @@ -1,66 +0,0 @@ -// 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 deleted file mode 100644 index da62da4ba492856b0d73a564c1bf9cdd60b5b742..0000000000000000000000000000000000000000 --- a/docs/examples/c/telnet_line_example.c +++ /dev/null @@ -1,54 +0,0 @@ -// 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=California.SanFrancisco groupid=2", - "meters.current 1648432611250 12.6 location=California.SanFrancisco groupid=2", - "meters.current 1648432611249 10.8 location=California.LosAngeles groupid=3", - "meters.current 1648432611250 11.3 location=California.LosAngeles groupid=3", - "meters.voltage 1648432611249 219 location=California.SanFrancisco groupid=2", - "meters.voltage 1648432611250 218 location=California.SanFrancisco groupid=2", - "meters.voltage 1648432611249 221 location=California.LosAngeles groupid=3", - "meters.voltage 1648432611250 217 location=California.LosAngeles 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 deleted file mode 100644 index b3aff79f3706e23aa74199a7f521f7912d2b0e45..0000000000000000000000000000000000000000 --- a/docs/examples/csharp/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -bin -obj -.vs -*.sln \ No newline at end of file diff --git a/docs/examples/csharp/AsyncQueryExample.cs b/docs/examples/csharp/AsyncQueryExample.cs deleted file mode 100644 index 3dabbebd1630a207af2e1b1b11cc4ba15bdd94a9..0000000000000000000000000000000000000000 --- a/docs/examples/csharp/AsyncQueryExample.cs +++ /dev/null @@ -1,238 +0,0 @@ -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 - -// 1538548685500 | 11.8 | 221 | 0.28 | california.losangeles | 2 | -// 1538548696600 | 13.4 | 223 | 0.29 | california.losangeles | 2 | -// 1538548685000 | 10.8 | 223 | 0.29 | california.losangeles | 3 | -// 1538548686500 | 11.5 | 221 | 0.35 | california.losangeles | 3 | -// 1538548685000 | 10.3 | 219 | 0.31 | california.sanfrancisco | 2 | -// 1538548695000 | 12.6 | 218 | 0.33 | california.sanfrancisco | 2 | -// 1538548696800 | 12.3 | 221 | 0.31 | california.sanfrancisco | 2 | -// 1538548696650 | 10.3 | 218 | 0.25 | california.sanfrancisco | 3 | -// async retrieve complete. \ No newline at end of file diff --git a/docs/examples/csharp/ConnectExample.cs b/docs/examples/csharp/ConnectExample.cs deleted file mode 100644 index f3548ee65daab8a59695499339a8f89b0aa33a10..0000000000000000000000000000000000000000 --- a/docs/examples/csharp/ConnectExample.cs +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 7b4453f4ac0b14dd76d166e395bdacb46a5d3fbc..0000000000000000000000000000000000000000 --- a/docs/examples/csharp/InfluxDBLineExample.cs +++ /dev/null @@ -1,77 +0,0 @@ -using TDengineDriver; - -namespace TDengineExample -{ - internal class InfluxDBLineExample - { - static void Main() - { - IntPtr conn = GetConnection(); - PrepareDatabase(conn); - string[] lines = { - "meters,location=California.LosAngeles,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249", - "meters,location=California.LosAngeles,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611250", - "meters,location=California.LosAngeles,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249", - "meters,location=California.LosAngeles,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 deleted file mode 100644 index 2c41acc5c9628befda7eb4ad5c30af5b921de948..0000000000000000000000000000000000000000 --- a/docs/examples/csharp/OptsJsonExample.cs +++ /dev/null @@ -1,76 +0,0 @@ -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\": \"California.SanFrancisco\", \"groupid\": 2}}," + - " {\"metric\": \"meters.voltage\", \"timestamp\": 1648432611249, \"value\": 219, \"tags\": {\"location\": \"California.LosAngeles\", \"groupid\": 1}}, " + - "{\"metric\": \"meters.current\", \"timestamp\": 1648432611250, \"value\": 12.6, \"tags\": {\"location\": \"California.SanFrancisco\", \"groupid\": 2}}," + - " {\"metric\": \"meters.voltage\", \"timestamp\": 1648432611250, \"value\": 221, \"tags\": {\"location\": \"California.LosAngeles\", \"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 deleted file mode 100644 index bb752db1afbbb2ef68df9ca25314c8b91cd9a266..0000000000000000000000000000000000000000 --- a/docs/examples/csharp/OptsTelnetExample.cs +++ /dev/null @@ -1,80 +0,0 @@ -using TDengineDriver; - -namespace TDengineExample -{ - internal class OptsTelnetExample - { - static void Main() - { - IntPtr conn = GetConnection(); - PrepareDatabase(conn); - string[] lines = { - "meters.current 1648432611249 10.3 location=California.SanFrancisco groupid=2", - "meters.current 1648432611250 12.6 location=California.SanFrancisco groupid=2", - "meters.current 1648432611249 10.8 location=California.LosAngeles groupid=3", - "meters.current 1648432611250 11.3 location=California.LosAngeles groupid=3", - "meters.voltage 1648432611249 219 location=California.SanFrancisco groupid=2", - "meters.voltage 1648432611250 218 location=California.SanFrancisco groupid=2", - "meters.voltage 1648432611249 221 location=California.LosAngeles groupid=3", - "meters.voltage 1648432611250 217 location=California.LosAngeles 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 deleted file mode 100644 index 97f0c456d412e2ed608c345ba87469d3f5ccfc15..0000000000000000000000000000000000000000 --- a/docs/examples/csharp/QueryExample.cs +++ /dev/null @@ -1,162 +0,0 @@ -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 California.SanFrancisco 2 -// 1648432611749 12.6 218 0.33 California.SanFrancisco 2 \ No newline at end of file diff --git a/docs/examples/csharp/SQLInsertExample.cs b/docs/examples/csharp/SQLInsertExample.cs deleted file mode 100644 index d5462c1062e01fd5c93bac983696d0350117ad92..0000000000000000000000000000000000000000 --- a/docs/examples/csharp/SQLInsertExample.cs +++ /dev/null @@ -1,69 +0,0 @@ -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(California.SanFrancisco, 2) VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000) ('2018-10-03 14:38:15.000', 12.60000, 218, 0.33000) ('2018-10-03 14:38:16.800', 12.30000, 221, 0.31000) " + - "d1002 USING power.meters TAGS(California.SanFrancisco, 3) VALUES('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000) " + - "d1003 USING power.meters TAGS(California.LosAngeles, 2) VALUES('2018-10-03 14:38:05.500', 11.80000, 221, 0.28000)('2018-10-03 14:38:16.600', 13.40000, 223, 0.29000) " + - "d1004 USING power.meters TAGS(California.LosAngeles, 3) VALUES('2018-10-03 14:38:05.000', 10.80000, 223, 0.29000)('2018-10-03 14:38:06.500', 11.50000, 221, 0.35000)"; - 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 deleted file mode 100644 index 6ade424b95d64529b7a40a782de13e3106d0c78a..0000000000000000000000000000000000000000 --- a/docs/examples/csharp/StmtInsertExample.cs +++ /dev/null @@ -1,115 +0,0 @@ -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("California.SanFrancisco"), 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 deleted file mode 100644 index 34509215da73ea6369eb95f458d622cd95a97932..0000000000000000000000000000000000000000 --- a/docs/examples/csharp/SubscribeDemo.cs +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 7a952fe7abd15798bc704de52aa72624e59061eb..0000000000000000000000000000000000000000 --- a/docs/examples/csharp/asyncquery.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - Exe - net6.0 - enable - enable - TDengineExample.AsyncQueryExample - - - - - - - diff --git a/docs/examples/csharp/connect.csproj b/docs/examples/csharp/connect.csproj deleted file mode 100644 index 27cffa30ae5a98277b74c63cf3d2c749ec67ce8d..0000000000000000000000000000000000000000 --- a/docs/examples/csharp/connect.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - Exe - net6.0 - enable - enable - TDengineExample.ConnectExample - - - - - - - diff --git a/docs/examples/csharp/influxdbline.csproj b/docs/examples/csharp/influxdbline.csproj deleted file mode 100644 index a8b197dc7167f229b903bfd010a9ff7282c9173b..0000000000000000000000000000000000000000 --- a/docs/examples/csharp/influxdbline.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - Exe - net6.0 - enable - enable - TDengineExample.InfluxDBLineExample - - - - - - - diff --git a/docs/examples/csharp/optsjson.csproj b/docs/examples/csharp/optsjson.csproj deleted file mode 100644 index b1bd83405efb1086b23134a9c875912a9c09e3f8..0000000000000000000000000000000000000000 --- a/docs/examples/csharp/optsjson.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - Exe - net6.0 - enable - enable - TDengineExample.OptsJsonExample - - - - - - - diff --git a/docs/examples/csharp/optstelnet.csproj b/docs/examples/csharp/optstelnet.csproj deleted file mode 100644 index 1ab41067715f8cb070e78aec2be59d686bac0e86..0000000000000000000000000000000000000000 --- a/docs/examples/csharp/optstelnet.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - Exe - net6.0 - enable - enable - TDengineExample.OptsTelnetExample - - - - - - - diff --git a/docs/examples/csharp/query.csproj b/docs/examples/csharp/query.csproj deleted file mode 100644 index 63f13c3ddbf13be9ffe5c39054cc6e4cae6001e7..0000000000000000000000000000000000000000 --- a/docs/examples/csharp/query.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - Exe - net6.0 - enable - enable - TDengineExample.QueryExample - - - - - - - diff --git a/docs/examples/csharp/sqlinsert.csproj b/docs/examples/csharp/sqlinsert.csproj deleted file mode 100644 index 0380395a5ad00d96418410b2f7974b294bf2bb07..0000000000000000000000000000000000000000 --- a/docs/examples/csharp/sqlinsert.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - Exe - net6.0 - enable - enable - TDengineExample.SQLInsertExample - - - - - - - diff --git a/docs/examples/csharp/stmtinsert.csproj b/docs/examples/csharp/stmtinsert.csproj deleted file mode 100644 index 8defb895eb2894c680fe1b9dd7346223f0f92df1..0000000000000000000000000000000000000000 --- a/docs/examples/csharp/stmtinsert.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - Exe - net6.0 - enable - enable - TDengineExample.StmtInsertExample - - - - - - - diff --git a/docs/examples/csharp/subscribe.csproj b/docs/examples/csharp/subscribe.csproj deleted file mode 100644 index 8286922c6f926b166f14983525e604ce9e13d74a..0000000000000000000000000000000000000000 --- a/docs/examples/csharp/subscribe.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - Exe - net6.0 - enable - enable - TDengineExample.SubscribeDemo - - - - - - - diff --git a/docs/examples/go/.gitignore b/docs/examples/go/.gitignore deleted file mode 100644 index b6128386c306834cddeb425f365720bb9c9ce790..0000000000000000000000000000000000000000 --- a/docs/examples/go/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -.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 deleted file mode 100644 index 2d36ef03ab049a313ed0416f552397ff252e022e..0000000000000000000000000000000000000000 --- a/docs/examples/go/connect/afconn/main.go +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index ba7ed0f728a1cd546dbc3199ce4c0dc854ebee91..0000000000000000000000000000000000000000 --- a/docs/examples/go/connect/cgoexample/main.go +++ /dev/null @@ -1,23 +0,0 @@ -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 a specified database named "dbName". diff --git a/docs/examples/go/connect/restexample/main.go b/docs/examples/go/connect/restexample/main.go deleted file mode 100644 index 1efc98b988c183c4c680884057bf2a72a9dd19e9..0000000000000000000000000000000000000000 --- a/docs/examples/go/connect/restexample/main.go +++ /dev/null @@ -1,23 +0,0 @@ -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 a specified database named "dbName". diff --git a/docs/examples/go/connect/wrapper/main.go b/docs/examples/go/connect/wrapper/main.go deleted file mode 100644 index d7e71a8baf229012b6944aad0eaac232924dd667..0000000000000000000000000000000000000000 --- a/docs/examples/go/connect/wrapper/main.go +++ /dev/null @@ -1,17 +0,0 @@ -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/connectexample/go.mod b/docs/examples/go/connectexample/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..8e3870da9b04afe2d1a6e6fb2c0b1bf279b066e6 --- /dev/null +++ b/docs/examples/go/connectexample/go.mod @@ -0,0 +1,11 @@ +module tdengine.com/example + +go 1.17 + +require github.com/taosdata/driver-go/v2 v2.0.1-0.20220523115057-e3107e343c03 + +require ( + github.com/json-iterator/go v1.1.12 // indirect + github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect +) diff --git a/docs/examples/go/connectexample/go.sum b/docs/examples/go/connectexample/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..0136c270d6d8fe733451ef8523ff05b633de6dc9 --- /dev/null +++ b/docs/examples/go/connectexample/go.sum @@ -0,0 +1,21 @@ +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/taosdata/driver-go/v2 v2.0.1-0.20220523115057-e3107e343c03 h1:uMJhzerYX73ksAuaOsVtIWk3q3m+6ckMuxT3RvA4HCw= +github.com/taosdata/driver-go/v2 v2.0.1-0.20220523115057-e3107e343c03/go.mod h1:ZAb4yDucTytX1Gy69F3nTRV+lEXmjkyF4J6OiYCR9NI= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/docs/examples/go/connectexample/main.go b/docs/examples/go/connectexample/main.go new file mode 100644 index 0000000000000000000000000000000000000000..d704468ce8c3abd077be9e99bd138ee2b9692e9b --- /dev/null +++ b/docs/examples/go/connectexample/main.go @@ -0,0 +1,24 @@ +package main + +import ( + "database/sql" + "fmt" + "os" + + _ "github.com/taosdata/driver-go/v2/taosRestful" +) + +func main() { + dsn := os.Getenv("TDENGINE_GO_DSN") + taos, err := sql.Open("taosRestful", dsn) + if err != nil { + fmt.Println("failed to connect TDengine, err:", err) + return + } + _, err = taos.Exec("select server_version()") + if err != nil { + fmt.Println(err) + } + fmt.Println("connect success") + defer taos.Close() +} diff --git a/docs/examples/go/go.mod b/docs/examples/go/go.mod deleted file mode 100644 index 5945e395e93b373d47fe71f3584c37fed9526638..0000000000000000000000000000000000000000 --- a/docs/examples/go/go.mod +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 6be375270e32a5091c015f88de52c9dda2246b59..0000000000000000000000000000000000000000 --- a/docs/examples/go/insert/json/main.go +++ /dev/null @@ -1,37 +0,0 @@ -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": "California.SanFrancisco", "groupid": 2}}, - {"metric": "meters.voltage", "timestamp": 1648432611249, "value": 219, "tags": {"location": "California.LosAngeles", "groupid": 1}}, - {"metric": "meters.current", "timestamp": 1648432611250, "value": 12.6, "tags": {"location": "California.SanFrancisco", "groupid": 2}}, - {"metric": "meters.voltage", "timestamp": 1648432611250, "value": 221, "tags": {"location": "California.LosAngeles", "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 deleted file mode 100644 index c17e1a5270850e6a8b497e0dbec4ae714ee1e2d6..0000000000000000000000000000000000000000 --- a/docs/examples/go/insert/line/main.go +++ /dev/null @@ -1,38 +0,0 @@ -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=California.LosAngeles,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249", - "meters,location=California.LosAngeles,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611250", - "meters,location=California.LosAngeles,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249", - "meters,location=California.LosAngeles,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/sql/main.go b/docs/examples/go/insert/sql/main.go deleted file mode 100644 index 6cd5f860e65f4fffd139668f69cc1772f5310eae..0000000000000000000000000000000000000000 --- a/docs/examples/go/insert/sql/main.go +++ /dev/null @@ -1,49 +0,0 @@ -package main - -import ( - "database/sql" - "fmt" - - _ "github.com/taosdata/driver-go/v2/taosRestful" -) - -func createStable(taos *sql.DB) { - _, err := taos.Exec("CREATE DATABASE power") - if err != nil { - fmt.Println("failed to create database, err:", err) - } - _, err = taos.Exec("CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)") - if err != nil { - fmt.Println("failed to create stable, err:", err) - } -} - -func insertData(taos *sql.DB) { - sql := `INSERT INTO power.d1001 USING power.meters TAGS(California.SanFrancisco, 2) VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000) ('2018-10-03 14:38:15.000', 12.60000, 218, 0.33000) ('2018-10-03 14:38:16.800', 12.30000, 221, 0.31000) - power.d1002 USING power.meters TAGS(California.SanFrancisco, 3) VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000) - power.d1003 USING power.meters TAGS(California.LosAngeles, 2) VALUES ('2018-10-03 14:38:05.500', 11.80000, 221, 0.28000) ('2018-10-03 14:38:16.600', 13.40000, 223, 0.29000) - power.d1004 USING power.meters TAGS(California.LosAngeles, 3) VALUES ('2018-10-03 14:38:05.000', 10.80000, 223, 0.29000) ('2018-10-03 14:38:06.500', 11.50000, 221, 0.35000)` - result, err := taos.Exec(sql) - if err != nil { - fmt.Println("failed to insert, err:", err) - return - } - rowsAffected, err := result.RowsAffected() - if err != nil { - fmt.Println("failed to get affected rows, err:", err) - return - } - fmt.Println("RowsAffected", rowsAffected) -} - -func main() { - var taosDSN = "root:taosdata@http(localhost:6041)/" - taos, err := sql.Open("taosRestful", taosDSN) - if err != nil { - fmt.Println("failed to connect TDengine, err:", err) - return - } - defer taos.Close() - createStable(taos) - insertData(taos) -} diff --git a/docs/examples/go/insert/stmt/main.go b/docs/examples/go/insert/stmt/main.go deleted file mode 100644 index 7093fdf1e52bc5a14fc92cec995fd81e70717d9f..0000000000000000000000000000000000000000 --- a/docs/examples/go/insert/stmt/main.go +++ /dev/null @@ -1,73 +0,0 @@ -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("California.SanFrancisco")).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 deleted file mode 100644 index 91fafbe71adbf60d9341b903f5a25708b7011852..0000000000000000000000000000000000000000 --- a/docs/examples/go/insert/telnet/main.go +++ /dev/null @@ -1,42 +0,0 @@ -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=California.SanFrancisco groupid=2", - "meters.current 1648432611250 12.6 location=California.SanFrancisco groupid=2", - "meters.current 1648432611249 10.8 location=California.LosAngeles groupid=3", - "meters.current 1648432611250 11.3 location=California.LosAngeles groupid=3", - "meters.voltage 1648432611249 219 location=California.SanFrancisco groupid=2", - "meters.voltage 1648432611250 218 location=California.SanFrancisco groupid=2", - "meters.voltage 1648432611249 221 location=California.LosAngeles groupid=3", - "meters.voltage 1648432611250 217 location=California.LosAngeles 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 deleted file mode 100644 index 7776ec8d3f268a3ef393d2097b71dc5681cf48d9..0000000000000000000000000000000000000000 --- a/docs/examples/go/query/async/main.go +++ /dev/null @@ -1,7 +0,0 @@ -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 deleted file mode 100644 index 0326c7a7da5da212f66b1421bb46e5972bef9609..0000000000000000000000000000000000000000 --- a/docs/examples/go/query/sync/main.go +++ /dev/null @@ -1,38 +0,0 @@ -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 deleted file mode 100644 index f4f5792e29436e539f301c14ce76607ad3e5593d..0000000000000000000000000000000000000000 --- a/docs/examples/go/rest/opentsdbjson/main.go +++ /dev/null @@ -1,45 +0,0 @@ -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 deleted file mode 100644 index c44521b34026ebf6f84f70022a7c2d1f83e9b781..0000000000000000000000000000000000000000 --- a/docs/examples/go/sub/main.go +++ /dev/null @@ -1,53 +0,0 @@ -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/php/connect.php b/docs/examples/php/connect.php deleted file mode 100644 index b825b447805a3923248042d2cdff79c51bdcdbe3..0000000000000000000000000000000000000000 --- a/docs/examples/php/connect.php +++ /dev/null @@ -1,20 +0,0 @@ -connect(); -} catch (TDengineException $e) { - // throw exception - throw $e; -} diff --git a/docs/examples/php/insert.php b/docs/examples/php/insert.php deleted file mode 100644 index 6e38fa0c46d31aa0a939d471ccbd255cfa453a16..0000000000000000000000000000000000000000 --- a/docs/examples/php/insert.php +++ /dev/null @@ -1,33 +0,0 @@ -connect(); - - // insert - $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(California.SanFrancisco, 2) VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000) ('2018-10-03 14:38:15.000', 12.60000, 218, 0.33000) ('2018-10-03 14:38:16.800', 12.30000, 221, 0.31000) - power.d1002 USING power.meters TAGS(California.SanFrancisco, 3) VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000) - power.d1003 USING power.meters TAGS(California.LosAngeles, 2) VALUES ('2018-10-03 14:38:05.500', 11.80000, 221, 0.28000) ('2018-10-03 14:38:16.600', 13.40000, 223, 0.29000) - power.d1004 USING power.meters TAGS(California.LosAngeles, 3) VALUES ('2018-10-03 14:38:05.000', 10.80000, 223, 0.29000) ('2018-10-03 14:38:06.500', 11.50000, 221, 0.35000) - SQL); - - // get affected rows - var_dump($resource->affectedRows()); -} catch (TDengineException $e) { - // throw exception - throw $e; -} diff --git a/docs/examples/php/insert_stmt.php b/docs/examples/php/insert_stmt.php deleted file mode 100644 index 99a9a6aef3f69a8880316355e17396e06ca985c9..0000000000000000000000000000000000000000 --- a/docs/examples/php/insert_stmt.php +++ /dev/null @@ -1,49 +0,0 @@ -connect(); - - // insert - $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(?, ?, ?, ?)'); - - // set table name and tags - $stmt->setTableNameTags('d1001', [ - // 支持格式同参数绑定 - [TDengine\TSDB_DATA_TYPE_BINARY, 'California.SanFrancisco'], - [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(); - - // get affected rows - var_dump($resource->affectedRows()); -} catch (TDengineException $e) { - // throw exception - throw $e; -} diff --git a/docs/examples/php/query.php b/docs/examples/php/query.php deleted file mode 100644 index 2607940ea06a70eaa30e4c165c05bd72aa89857c..0000000000000000000000000000000000000000 --- a/docs/examples/php/query.php +++ /dev/null @@ -1,23 +0,0 @@ -connect(); - - $resource = $connection->query('SELECT ts, current FROM meters LIMIT 2'); - var_dump($resource->fetch()); -} catch (TDengineException $e) { - // throw exception - throw $e; -} diff --git a/docs/examples/python/.gitignore b/docs/examples/python/.gitignore index 723ef36f4e4f32c4560383aa5987c575a30c6535..0fd214ce1d42db2249b3e601622981a796d3558e 100644 --- a/docs/examples/python/.gitignore +++ b/docs/examples/python/.gitignore @@ -1 +1,4 @@ -.idea \ No newline at end of file +.idea +.vscode +*.un~ +*~ diff --git a/docs/examples/python/async_query_example.py b/docs/examples/python/async_query_example.py deleted file mode 100644 index a78f44230a34d40a5326dea367bbad11a6e51da2..0000000000000000000000000000000000000000 --- a/docs/examples/python/async_query_example.py +++ /dev/null @@ -1,72 +0,0 @@ -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 deleted file mode 100644 index 6a67434f876f159cf32069a55e9527ca19034640..0000000000000000000000000000000000000000 --- a/docs/examples/python/bind_param_example.py +++ /dev/null @@ -1,60 +0,0 @@ -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, 'California.SanFrancisco', 2), - ('d1001', '2018-10-03 14:38:15.000', 12.60000, 218, 0.33000, 'California.SanFrancisco', 2), - ('d1001', '2018-10-03 14:38:16.800', 12.30000, 221, 0.31000, 'California.SanFrancisco', 2), - ('d1002', '2018-10-03 14:38:16.650', 10.30000, 218, 0.25000, 'California.SanFrancisco', 3), - ('d1003', '2018-10-03 14:38:05.500', 11.80000, 221, 0.28000, 'California.LosAngeles', 2), - ('d1003', '2018-10-03 14:38:16.600', 13.40000, 223, 0.29000, 'California.LosAngeles', 2), - ('d1004', '2018-10-03 14:38:05.000', 10.80000, 223, 0.29000, 'California.LosAngeles', 3), - ('d1004', '2018-10-03 14:38:06.500', 11.50000, 221, 0.35000, 'California.LosAngeles', 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 deleted file mode 100644 index 56942ef57085766cd128b03cabb7a357587eab16..0000000000000000000000000000000000000000 --- a/docs/examples/python/conn_native_pandas.py +++ /dev/null @@ -1,19 +0,0 @@ -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 ... location groupid -# 0 2018-10-03 14:38:05.500 11.8 ... california.losangeles 2 -# 1 2018-10-03 14:38:16.600 13.4 ... california.losangeles 2 -# 2 2018-10-03 14:38:05.000 10.8 ... california.losangeles 3 diff --git a/docs/examples/python/connect_cloud_example.py b/docs/examples/python/connect_cloud_example.py index 493ff98eaf8aa82c244f993cd7d8f37cb962a4d8..ac2345ddbe23374463ea196fdd2e309843afd2b1 100644 --- a/docs/examples/python/connect_cloud_example.py +++ b/docs/examples/python/connect_cloud_example.py @@ -1,3 +1,6 @@ +from dotenv import load_dotenv +load_dotenv() # read .env file from current working directory + # ANCHOR: connect import taosrest import os @@ -6,7 +9,6 @@ url = os.environ["TDENGINE_CLOUD_URL"] token = os.environ["TDENGINE_CLOUD_TOKEN"] conn = taosrest.connect(url=url, token=token) - # ANCHOR_END: connect # ANCHOR: basic from taosrest import TaosRestCursor diff --git a/docs/examples/python/connect_example.py b/docs/examples/python/connect_example.py deleted file mode 100644 index 719af79fd12c14cc16e4e3e3c4d6362da5a7520d..0000000000000000000000000000000000000000 --- a/docs/examples/python/connect_example.py +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index c17e9795b58724f6646b8d7c0f84047098a93d69..0000000000000000000000000000000000000000 --- a/docs/examples/python/connect_native_reference.py +++ /dev/null @@ -1,20 +0,0 @@ -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/connection_usage_native_reference.py b/docs/examples/python/connection_usage_native_reference.py deleted file mode 100644 index 4803511e427bf4d906fd3a14ff6faf5a000da96c..0000000000000000000000000000000000000000 --- a/docs/examples/python/connection_usage_native_reference.py +++ /dev/null @@ -1,45 +0,0 @@ -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 deleted file mode 100644 index a5103810f0199708f94b5c36e1dc080b7998e420..0000000000000000000000000000000000000000 --- a/docs/examples/python/cursor_usage_native_reference.py +++ /dev/null @@ -1,32 +0,0 @@ -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 deleted file mode 100644 index 59554465c0891c80f0507656fcc79538c3811fa7..0000000000000000000000000000000000000000 --- a/docs/examples/python/handle_exception.py +++ /dev/null @@ -1,19 +0,0 @@ -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/native_insert_example.py b/docs/examples/python/native_insert_example.py deleted file mode 100644 index 3b6b73cb2236c8d9d11019349f99f79135a5c1d6..0000000000000000000000000000000000000000 --- a/docs/examples/python/native_insert_example.py +++ /dev/null @@ -1,60 +0,0 @@ -import taos - -lines = ["d1001,2018-10-03 14:38:05.000,10.30000,219,0.31000,California.SanFrancisco,2", - "d1004,2018-10-03 14:38:05.000,10.80000,223,0.29000,California.LosAngeles,3", - "d1003,2018-10-03 14:38:05.500,11.80000,221,0.28000,California.LosAngeles,2", - "d1004,2018-10-03 14:38:06.500,11.50000,221,0.35000,California.LosAngeles,3", - "d1002,2018-10-03 14:38:16.650,10.30000,218,0.25000,California.SanFrancisco,3", - "d1001,2018-10-03 14:38:15.000,12.60000,218,0.33000,California.SanFrancisco,2", - "d1001,2018-10-03 14:38:16.800,12.30000,221,0.31000,California.SanFrancisco,2", - "d1003,2018-10-03 14:38:16.600,13.40000,223,0.29000,California.LosAngeles,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(California.SanFrancisco, 2) VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000) ('2018-10-03 14:38:15.000', 12.60000, 218, 0.33000) ('2018-10-03 14:38:16.800', 12.30000, 221, 0.31000) -# d1002 USING meters TAGS(California.SanFrancisco, 3) VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000) -# d1003 USING meters TAGS(California.LosAngeles, 2) VALUES ('2018-10-03 14:38:05.500', 11.80000, 221, 0.28000) ('2018-10-03 14:38:16.600', 13.40000, 223, 0.29000) -# d1004 USING meters TAGS(California.LosAngeles, 3) VALUES ('2018-10-03 14:38:05.000', 10.80000, 223, 0.29000) ('2018-10-03 14:38:06.500', 11.50000, 221, 0.35000) - -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 deleted file mode 100644 index 8afd7f07358d7e9c9a3677ee04f8eb92aae6856b..0000000000000000000000000000000000000000 --- a/docs/examples/python/query_example.py +++ /dev/null @@ -1,42 +0,0 @@ -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 fields[1]: {name: ts, type: 9, bytes: 8} -# ======================Iterate on result========================= -# ('d1003', datetime.datetime(2018, 10, 3, 14, 38, 5, 500000), 11.800000190734863, 221, 0.2800000011920929, 'california.losangeles', 2) -# ('d1003', datetime.datetime(2018, 10, 3, 14, 38, 16, 600000), 13.399999618530273, 223, 0.28999999165534973, 'california.losangeles', 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, 500000), 'current': 11.800000190734863}, -# {'ts': datetime.datetime(2018, 10, 3, 14, 38, 16, 600000), 'current': 13.399999618530273}] -# 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 deleted file mode 100644 index 59c629df95fdc7dcee8d764d061afeb360b51dfc..0000000000000000000000000000000000000000 --- a/docs/examples/python/rest_client_example.py +++ /dev/null @@ -1,9 +0,0 @@ -from taosrest import RestClient - -client = RestClient("http://localhost:6041", user="root", password="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 deleted file mode 100644 index 6cba0d3f73cdaa408309de93652ed8f346c8f759..0000000000000000000000000000000000000000 --- a/docs/examples/python/result_set_examples.py +++ /dev/null @@ -1,33 +0,0 @@ -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 deleted file mode 100644 index db9d49c3f4f8122634800c02a683d4cb022a7ba0..0000000000000000000000000000000000000000 --- a/docs/examples/python/subscribe_demo.py +++ /dev/null @@ -1,38 +0,0 @@ -""" -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