From 23b54e1df48a8586aa5238a95494083ed3ad7ee3 Mon Sep 17 00:00:00 2001 From: menshibin Date: Tue, 13 Aug 2024 10:39:43 +0800 Subject: [PATCH 01/22] modify alert sql --- docs/examples/python/tmq_native.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/examples/python/tmq_native.py b/docs/examples/python/tmq_native.py index 64e447384c..a913d945c9 100644 --- a/docs/examples/python/tmq_native.py +++ b/docs/examples/python/tmq_native.py @@ -163,7 +163,7 @@ if __name__ == "__main__": seek_offset(consumer) commit_offset(consumer) consumer.unsubscribe() - print("Consumer unsubscribed successfully."); + print("Consumer unsubscribed successfully.") except Exception as err: print(f"Failed to stmt consumer. ErrMessage:{err}") finally: From 1397fbe2a24122c6f93b406829a246461251a651 Mon Sep 17 00:00:00 2001 From: sheyanjie-qq <249478495@qq.com> Date: Wed, 14 Aug 2024 16:25:22 +0800 Subject: [PATCH 02/22] modify connector sample code log --- docs/examples/csharp/nativesml/Program.cs | 6 +- docs/examples/csharp/stmtInsert/Program.cs | 6 +- docs/examples/csharp/subscribe/Program.cs | 24 +- docs/examples/csharp/wsInsert/Program.cs | 22 +- docs/examples/csharp/wsStmt/Program.cs | 6 +- docs/examples/csharp/wssml/Program.cs | 8 +- docs/examples/csharp/wssubscribe/Program.cs | 24 +- docs/examples/go/queryreqid/main.go | 6 +- docs/examples/go/schemaless/native/main.go | 10 +- docs/examples/go/schemaless/ws/main.go | 8 +- docs/examples/go/sqlquery/main.go | 21 +- docs/examples/go/stmt/native/main.go | 16 +- docs/examples/go/stmt/ws/main.go | 20 +- docs/examples/go/tmq/native/main.go | 24 +- docs/examples/go/tmq/ws/main.go | 24 +- docs/examples/java/pom.xml | 18 + .../com/taos/example/ConsumerLoopFull.java | 384 ++++++++++++++++++ .../main/java/com/taos/example/DruidDemo.java | 36 ++ .../java/com/taos/example/GeometryDemo.java | 190 +++++++++ .../java/com/taos/example/HikariDemo.java | 37 ++ .../com/taos/example/JNIConnectExample.java | 48 +-- .../java/com/taos/example/JdbcBasicDemo.java | 125 ++++++ .../com/taos/example/JdbcCreatDBDemo.java | 53 +++ .../com/taos/example/JdbcInsertDataDemo.java | 55 +++ .../java/com/taos/example/JdbcQueryDemo.java | 55 +++ .../java/com/taos/example/JdbcReqIdDemo.java | 64 +++ .../example/ParameterBindingBasicDemo.java | 90 ++++ .../example/ParameterBindingFullDemo.java | 325 +++++++++++++++ .../com/taos/example/RESTConnectExample.java | 32 +- .../com/taos/example/SchemalessJniTest.java | 47 +++ .../com/taos/example/SchemalessWsTest.java | 47 +++ .../src/main/java/com/taos/example/Util.java | 25 ++ .../com/taos/example/WSConnectExample.java | 16 +- .../example/WSParameterBindingBasicDemo.java | 67 +++ .../example/WSParameterBindingFullDemo.java | 180 ++++++++ .../com/taos/example/WsConsumerLoopFull.java | 384 ++++++++++++++++++ .../node/websocketexample/line_example.js | 4 +- .../node/websocketexample/sql_example.js | 51 +-- .../node/websocketexample/stmt_example.js | 4 +- .../node/websocketexample/tmq_example.js | 17 +- .../node/websocketexample/tmq_seek_example.js | 4 +- docs/examples/python/connect_example.py | 4 +- docs/examples/python/connect_rest_example.py | 2 +- .../python/connect_websocket_examples.py | 2 +- docs/examples/python/create_db_native.py | 2 +- docs/examples/python/create_db_rest.py | 2 +- docs/examples/python/create_db_ws.py | 2 +- docs/examples/python/insert_native.py | 2 +- docs/examples/python/insert_rest.py | 2 +- docs/examples/python/insert_ws.py | 2 +- docs/examples/python/query_native.py | 8 +- docs/examples/python/query_rest.py | 6 +- docs/examples/python/query_ws.py | 6 +- docs/examples/python/reqid_native.py | 2 +- docs/examples/python/reqid_rest.py | 2 +- docs/examples/python/reqid_ws.py | 2 +- docs/examples/python/schemaless_native.py | 2 +- docs/examples/python/schemaless_ws.py | 4 +- docs/examples/python/stmt_native.py | 2 +- docs/examples/python/stmt_ws.py | 2 +- docs/examples/python/tmq_native.py | 11 +- docs/examples/python/tmq_websocket_example.py | 13 +- .../rust/nativeexample/examples/connect.rs | 2 +- .../rust/nativeexample/examples/createdb.rs | 4 +- .../rust/nativeexample/examples/insert.rs | 2 +- .../rust/nativeexample/examples/query.rs | 10 +- .../rust/nativeexample/examples/schemaless.rs | 6 +- .../rust/nativeexample/examples/stmt.rs | 26 +- .../rust/nativeexample/examples/tmq.rs | 16 +- .../rust/restexample/examples/connect.rs | 2 +- .../rust/restexample/examples/createdb.rs | 4 +- .../rust/restexample/examples/insert.rs | 2 +- .../rust/restexample/examples/query.rs | 10 +- .../rust/restexample/examples/schemaless.rs | 15 +- .../rust/restexample/examples/stmt.rs | 26 +- .../examples/rust/restexample/examples/tmq.rs | 10 +- docs/zh/08-develop/01-connect/index.md | 4 +- docs/zh/08-develop/02-sql.md | 8 +- docs/zh/08-develop/04-schemaless.md | 4 +- docs/zh/08-develop/05-stmt.md | 4 +- docs/zh/08-develop/07-tmq.md | 28 +- docs/zh/14-reference/05-connector/14-java.mdx | 2 +- .../taosdata/example/ConsumerLoopFull.java | 99 +++-- .../com/taosdata/example/JdbcCreatDBDemo.java | 14 +- .../taosdata/example/JdbcInsertDataDemo.java | 13 +- .../com/taosdata/example/JdbcQueryDemo.java | 22 +- .../com/taosdata/example/JdbcReqIdDemo.java | 13 +- .../example/ParameterBindingBasicDemo.java | 13 +- .../taosdata/example/SchemalessJniTest.java | 13 +- .../taosdata/example/SchemalessWsTest.java | 13 +- .../example/WSParameterBindingBasicDemo.java | 13 +- .../taosdata/example/WsConsumerLoopFull.java | 108 +++-- .../java/com/taosdata/example/DruidDemo.java | 48 +-- .../java/com/taosdata/example/HikariDemo.java | 48 +-- 94 files changed, 2774 insertions(+), 491 deletions(-) create mode 100644 docs/examples/java/src/main/java/com/taos/example/ConsumerLoopFull.java create mode 100644 docs/examples/java/src/main/java/com/taos/example/DruidDemo.java create mode 100644 docs/examples/java/src/main/java/com/taos/example/GeometryDemo.java create mode 100644 docs/examples/java/src/main/java/com/taos/example/HikariDemo.java create mode 100644 docs/examples/java/src/main/java/com/taos/example/JdbcBasicDemo.java create mode 100644 docs/examples/java/src/main/java/com/taos/example/JdbcCreatDBDemo.java create mode 100644 docs/examples/java/src/main/java/com/taos/example/JdbcInsertDataDemo.java create mode 100644 docs/examples/java/src/main/java/com/taos/example/JdbcQueryDemo.java create mode 100644 docs/examples/java/src/main/java/com/taos/example/JdbcReqIdDemo.java create mode 100644 docs/examples/java/src/main/java/com/taos/example/ParameterBindingBasicDemo.java create mode 100644 docs/examples/java/src/main/java/com/taos/example/ParameterBindingFullDemo.java create mode 100644 docs/examples/java/src/main/java/com/taos/example/SchemalessJniTest.java create mode 100644 docs/examples/java/src/main/java/com/taos/example/SchemalessWsTest.java create mode 100644 docs/examples/java/src/main/java/com/taos/example/Util.java create mode 100644 docs/examples/java/src/main/java/com/taos/example/WSParameterBindingBasicDemo.java create mode 100644 docs/examples/java/src/main/java/com/taos/example/WSParameterBindingFullDemo.java create mode 100644 docs/examples/java/src/main/java/com/taos/example/WsConsumerLoopFull.java diff --git a/docs/examples/csharp/nativesml/Program.cs b/docs/examples/csharp/nativesml/Program.cs index cfee07eee0..047222c4f4 100644 --- a/docs/examples/csharp/nativesml/Program.cs +++ b/docs/examples/csharp/nativesml/Program.cs @@ -42,16 +42,16 @@ namespace TDengineExample catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to insert data with schemaless; ErrCode:" + e.Code + "; ErrMessage: " + e.Error); + Console.WriteLine("Failed to insert data with schemaless, ErrCode: " + e.Code + ", ErrMessage: " + e.Error); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to insert data with schemaless; Err:" + e.Message); + Console.WriteLine("Failed to insert data with schemaless, ErrMessage:" + e.Message); throw; } } // ANCHOR_END: main } -} \ No newline at end of file +} diff --git a/docs/examples/csharp/stmtInsert/Program.cs b/docs/examples/csharp/stmtInsert/Program.cs index 60d1a58e55..b317da2fc1 100644 --- a/docs/examples/csharp/stmtInsert/Program.cs +++ b/docs/examples/csharp/stmtInsert/Program.cs @@ -62,16 +62,16 @@ namespace TDengineExample catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to insert to table meters using stmt, url: " + connectionString + "; ErrCode:" + e.Code + "; ErrMessage: " + e.Error); + Console.WriteLine("Failed to insert to table meters using stmt, ErrCode: " + e.Code + ", ErrMessage: " + e.Error); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to insert to table meters using stmt, url: " + connectionString + "; ErrMessage: " + e.Message); + Console.WriteLine("Failed to insert to table meters using stmt, ErrMessage: " + e.Message); throw; } } // ANCHOR_END: main } -} \ No newline at end of file +} diff --git a/docs/examples/csharp/subscribe/Program.cs b/docs/examples/csharp/subscribe/Program.cs index fa61435b03..4138194800 100644 --- a/docs/examples/csharp/subscribe/Program.cs +++ b/docs/examples/csharp/subscribe/Program.cs @@ -91,14 +91,14 @@ namespace TMQExample catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to create native consumer, host : " + host + "; ErrCode:" + e.Code + - "; ErrMessage: " + e.Error); + Console.WriteLine("Failed to create native consumer, host: " + host + ", ErrCode:" + e.Code + + ", ErrMessage: " + e.Error); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to create native consumer, host : " + host + "; ErrMessage: " + e.Message); + Console.WriteLine("Failed to create native consumer, host: " + host + ", ErrMessage: " + e.Message); throw; } @@ -133,13 +133,13 @@ namespace TMQExample catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to poll data; ErrCode:" + e.Code + "; ErrMessage: " + e.Error); + Console.WriteLine("Failed to poll data, ErrCode: " + e.Code + ", ErrMessage: " + e.Error); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to poll data; ErrMessage:" + e.Message); + Console.WriteLine("Failed to poll data, ErrMessage: " + e.Message); throw; } // ANCHOR_END: subscribe @@ -163,13 +163,13 @@ namespace TMQExample catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Seek example failed; ErrCode:" + e.Code + "; ErrMessage: " + e.Error); + Console.WriteLine("Failed to execute seek example, ErrCode: " + e.Code + ", ErrMessage: " + e.Error); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Seek example failed; ErrMessage: " + e.Message); + Console.WriteLine("Failed to execute seek example, ErrMessage: " + e.Message); throw; } // ANCHOR_END: seek @@ -197,13 +197,13 @@ namespace TMQExample catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to execute consumer functions. ErrCode:" + e.Code + "; ErrMessage: " + e.Error); + Console.WriteLine("Failed to execute commit example, ErrCode:" + e.Code + ", ErrMessage: " + e.Error); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to execute consumer functions. ErrMessage:" + e.Message); + Console.WriteLine("Failed to execute commit example, ErrMessage: " + e.Message); throw; } } @@ -221,13 +221,13 @@ namespace TMQExample catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to unsubscribe consumer. ErrCode:" + e.Code + "; ErrMessage: " + e.Error); + Console.WriteLine("Failed to unsubscribe consumer, ErrCode: " + e.Code + ", ErrMessage: " + e.Error); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to unsubscribe consumer. Err: " + e.Message); + Console.WriteLine("Failed to unsubscribe consumer, ErrMessage: " + e.Message); throw; } finally @@ -239,4 +239,4 @@ namespace TMQExample // ANCHOR_END: close } } -} \ No newline at end of file +} diff --git a/docs/examples/csharp/wsInsert/Program.cs b/docs/examples/csharp/wsInsert/Program.cs index cdddf27f42..36b884a522 100644 --- a/docs/examples/csharp/wsInsert/Program.cs +++ b/docs/examples/csharp/wsInsert/Program.cs @@ -52,13 +52,13 @@ namespace Examples catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to create db and table,url:" + connectionString +"; ErrCode:" + e.Code + "; ErrMessage: " + e.Error); + Console.WriteLine("Failed to create database power or stable meters, ErrCode: " + e.Code + ", ErrMessage: " + e.Error); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to create db and table, url:" + connectionString + "; ErrMessage: " + e.Message); + Console.WriteLine("Failed to create database power or stable meters, ErrMessage: " + e.Message); throw; } // ANCHOR_END: create_db_and_table @@ -85,13 +85,13 @@ namespace Examples catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to insert data to power.meters, url:" + connectionString + "; ErrCode:" + e.Code + "; ErrMessage: " + e.Error); + Console.WriteLine("Failed to insert data to power.meters, ErrCode: " + e.Code + ", ErrMessage: " + e.Error); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to insert data to power.meters, url:" + connectionString + "; ErrMessage: " + e.Message); + Console.WriteLine("Failed to insert data to power.meters, ErrMessage: " + e.Message); throw; } // ANCHOR_END: insert_data @@ -100,10 +100,10 @@ namespace Examples private static void QueryData(ITDengineClient client,string connectionString) { // ANCHOR: select_data + // query data, make sure the database and table are created before + var query = "SELECT ts, current, location FROM power.meters limit 100"; try { - // query data, make sure the database and table are created before - var query = "SELECT ts, current, location FROM power.meters limit 100"; using (var rows = client.Query(query)) { while (rows.Read()) @@ -119,13 +119,13 @@ namespace Examples catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to query data from power.meters, url:" + connectionString + "; ErrCode:" + e.Code + "; ErrMessage: " + e.Error); + Console.WriteLine("Failed to query data from power.meters, sql: " + query + ", ErrCode: " + e.Code + ", ErrMessage: " + e.Error); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to query data from power.meters, url:" + connectionString + "; ErrMessage: " + e.Message); + Console.WriteLine("Failed to query data from power.meters, sql: " + query + ", ErrMessage: " + e.Message); throw; } // ANCHOR_END: select_data @@ -155,16 +155,16 @@ namespace Examples catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to execute sql with reqId: " + reqId + ", url:" + connectionString + "; ErrCode:" + e.Code + "; ErrMessage: " + e.Error); + Console.WriteLine("Failed to execute sql with reqId: " + reqId + ", ErrCode: " + e.Code + ", ErrMessage: " + e.Error); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to execute sql with reqId: " + reqId + ", url:" + connectionString + "; ErrMessage: " + e.Message); + Console.WriteLine("Failed to execute sql with reqId: " + reqId + ", ErrMessage: " + e.Message); throw; } // ANCHOR_END: query_id } } -} \ No newline at end of file +} diff --git a/docs/examples/csharp/wsStmt/Program.cs b/docs/examples/csharp/wsStmt/Program.cs index 394165f109..fa0365f418 100644 --- a/docs/examples/csharp/wsStmt/Program.cs +++ b/docs/examples/csharp/wsStmt/Program.cs @@ -63,16 +63,16 @@ namespace Examples catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to insert to table meters using stmt, url: " + connectionString + "; ErrCode:" + e.Code + "; ErrMessage: " + e.Error); + Console.WriteLine("Failed to insert to table meters using stmt, ErrCode: " + e.Code + ", ErrMessage: " + e.Error); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to insert to table meters using stmt, url: " + connectionString + "; ErrMessage: " + e.Message); + Console.WriteLine("Failed to insert to table meters using stmt, ErrMessage: " + e.Message); throw; } } // ANCHOR_END: main } -} \ No newline at end of file +} diff --git a/docs/examples/csharp/wssml/Program.cs b/docs/examples/csharp/wssml/Program.cs index 94ee86919b..3bb5eea70c 100644 --- a/docs/examples/csharp/wssml/Program.cs +++ b/docs/examples/csharp/wssml/Program.cs @@ -44,17 +44,17 @@ namespace TDengineExample catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to insert data with schemaless, host:" + host + "; ErrCode:" + e.Code + - "; ErrMessage: " + e.Error); + Console.WriteLine("Failed to insert data with schemaless, ErrCode: " + e.Code + + ", ErrMessage: " + e.Error); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to insert data with schemaless, host:" + host + "; ErrMessage: " + e.Message); + Console.WriteLine("Failed to insert data with schemaless, ErrMessage: " + e.Message); throw; } } // ANCHOR_END: main } -} \ No newline at end of file +} diff --git a/docs/examples/csharp/wssubscribe/Program.cs b/docs/examples/csharp/wssubscribe/Program.cs index 9974c87906..21abe10847 100644 --- a/docs/examples/csharp/wssubscribe/Program.cs +++ b/docs/examples/csharp/wssubscribe/Program.cs @@ -96,14 +96,14 @@ namespace TMQExample catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to create websocket consumer, host : " + host + "; ErrCode:" + e.Code + - "; ErrMessage: " + e.Error); + Console.WriteLine("Failed to create websocket consumer, host: " + host + ", ErrCode: " + e.Code + + ", ErrMessage: " + e.Error); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to create websocket consumer, host : " + host + "; ErrMessage: " + e.Message); + Console.WriteLine("Failed to create websocket consumer, host: " + host + ", ErrMessage: " + e.Message); throw; } @@ -138,13 +138,13 @@ namespace TMQExample catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to poll data; ErrCode:" + e.Code + "; ErrMessage: " + e.Error); + Console.WriteLine("Failed to poll data, ErrCode: " + e.Code + ", ErrMessage: " + e.Error); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to poll data; ErrMessage:" + e.Message); + Console.WriteLine("Failed to poll data, ErrMessage: " + e.Message); throw; } // ANCHOR_END: subscribe @@ -168,13 +168,13 @@ namespace TMQExample catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Seek example failed; ErrCode:" + e.Code + "; ErrMessage: " + e.Error); + Console.WriteLine("Failed to execute seek example, ErrCode: " + e.Code + ", ErrMessage: " + e.Error); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Seek example failed; ErrMessage: " + e.Message); + Console.WriteLine("Failed to execute seek example, ErrMessage: " + e.Message); throw; } // ANCHOR_END: seek @@ -202,13 +202,13 @@ namespace TMQExample catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to execute consumer functions. ErrCode:" + e.Code + "; ErrMessage: " + e.Error); + Console.WriteLine("Failed to execute commit example, ErrCode: " + e.Code + ", ErrMessage: " + e.Error); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to execute consumer functions. ErrMessage:" + e.Message); + Console.WriteLine("Failed to execute commit example, ErrMessage: " + e.Message); throw; } } @@ -226,13 +226,13 @@ namespace TMQExample catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to unsubscribe consumer. ErrCode:" + e.Code + "; ErrMessage: " + e.Error); + Console.WriteLine("Failed to unsubscribe consumer, ErrCode :" + e.Code + ", ErrMessage: " + e.Error); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to unsubscribe consumer. Err: " + e.Message); + Console.WriteLine("Failed to unsubscribe consumer, ErrMessage: " + e.Message); throw; } finally @@ -244,4 +244,4 @@ namespace TMQExample // ANCHOR_END: close } } -} \ No newline at end of file +} diff --git a/docs/examples/go/queryreqid/main.go b/docs/examples/go/queryreqid/main.go index 045f0f8901..39d1d6bd5e 100644 --- a/docs/examples/go/queryreqid/main.go +++ b/docs/examples/go/queryreqid/main.go @@ -45,14 +45,14 @@ func main() { func initEnv(conn *sql.DB) { _, err := conn.Exec("CREATE DATABASE IF NOT EXISTS power") if err != nil { - log.Fatal("Create database error: ", err) + log.Fatal("Create database power error: ", err) } _, err = conn.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))") if err != nil { - log.Fatal("Create table error: ", err) + log.Fatal("Create stable meters error: ", err) } _, err = conn.Exec("INSERT INTO power.d1001 USING power.meters TAGS (2, 'California.SanFrancisco') VALUES (NOW , 10.2, 219, 0.32)") if err != nil { - log.Fatal("Insert data error: ", err) + log.Fatal("Insert data to power.meters error: ", err) } } diff --git a/docs/examples/go/schemaless/native/main.go b/docs/examples/go/schemaless/native/main.go index 6caa8bb4cb..36cdee70ac 100644 --- a/docs/examples/go/schemaless/native/main.go +++ b/docs/examples/go/schemaless/native/main.go @@ -20,26 +20,26 @@ func main() { defer conn.Close() _, err = conn.Exec("CREATE DATABASE IF NOT EXISTS power") if err != nil { - log.Fatalln("Failed to create db host: " + host + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to create database power, ErrMessage: " + err.Error()) } _, err = conn.Exec("USE power") if err != nil { - log.Fatalln("Failed to use db host: " + host + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to use database power, ErrMessage: " + err.Error()) } // insert influxdb line protocol err = conn.InfluxDBInsertLines([]string{lineDemo}, "ms") if err != nil { - log.Fatalln("Failed to insert data with schemaless, host: " + host + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to insert data with schemaless, data:" + lineDemo + ", ErrMessage: " + err.Error()) } // insert opentsdb telnet protocol err = conn.OpenTSDBInsertTelnetLines([]string{telnetDemo}) if err != nil { - log.Fatalln("Failed to insert data with schemaless, host: " + host + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to insert data with schemaless, data:" + telnetDemo + ", ErrMessage: " + err.Error()) } // insert opentsdb json protocol err = conn.OpenTSDBInsertJsonPayload(jsonDemo) if err != nil { - log.Fatalln("Failed to insert data with schemaless, host: " + host + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to insert data with schemaless, data:" + jsonDemo + ", ErrMessage: " + err.Error()) } fmt.Println("Inserted data with schemaless successfully.") } diff --git a/docs/examples/go/schemaless/ws/main.go b/docs/examples/go/schemaless/ws/main.go index 8507a70811..df1a14ee09 100644 --- a/docs/examples/go/schemaless/ws/main.go +++ b/docs/examples/go/schemaless/ws/main.go @@ -25,7 +25,7 @@ func main() { defer db.Close() _, err = db.Exec("CREATE DATABASE IF NOT EXISTS power") if err != nil { - log.Fatalln("Failed to create db host: " + host + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to create database power, ErrMessage: " + err.Error()) } s, err := schemaless.NewSchemaless(schemaless.NewConfig("ws://localhost:6041", 1, schemaless.SetDb("power"), @@ -40,17 +40,17 @@ func main() { // insert influxdb line protocol err = s.Insert(lineDemo, schemaless.InfluxDBLineProtocol, "ms", 0, common.GetReqID()) if err != nil { - log.Fatalln("Failed to insert data with schemaless, host:" + host + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to insert data with schemaless, data:" + lineDemo + ", ErrMessage: " + err.Error()) } // insert opentsdb telnet line protocol err = s.Insert(telnetDemo, schemaless.OpenTSDBTelnetLineProtocol, "ms", 0, common.GetReqID()) if err != nil { - log.Fatalln("Failed to insert data with schemaless, host: " + host + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to insert data with schemaless, data: " + telnetDemo + ", ErrMessage: " + err.Error()) } // insert opentsdb json format protocol err = s.Insert(jsonDemo, schemaless.OpenTSDBJsonFormatProtocol, "s", 0, common.GetReqID()) if err != nil { - log.Fatalln("Failed to insert data with schemaless, host: " + host + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to insert data with schemaless, data: " + jsonDemo + ", ErrMessage: " + err.Error()) } fmt.Println("Inserted data with schemaless successfully.") } diff --git a/docs/examples/go/sqlquery/main.go b/docs/examples/go/sqlquery/main.go index 1301c79325..f0e0f1c97e 100644 --- a/docs/examples/go/sqlquery/main.go +++ b/docs/examples/go/sqlquery/main.go @@ -13,29 +13,29 @@ func main() { var taosDSN = "root:taosdata@tcp(localhost:6030)/" db, err := sql.Open("taosSql", taosDSN) if err != nil { - log.Fatalln("Failed to connect to " + taosDSN + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to connect to " + taosDSN + ", ErrMessage: " + err.Error()) } defer db.Close() // ANCHOR: create_db_and_table // create database res, err := db.Exec("CREATE DATABASE IF NOT EXISTS power") if err != nil { - log.Fatalln("Failed to create db, url:" + taosDSN + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to create database power, ErrMessage: " + err.Error()) } rowsAffected, err := res.RowsAffected() if err != nil { - log.Fatalln("Failed to get create db rowsAffected, url:" + taosDSN + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to get create database rowsAffected, ErrMessage: " + err.Error()) } // you can check rowsAffected here fmt.Println("Create database power successfully, rowsAffected: ", rowsAffected) // create table res, err = db.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))") if err != nil { - log.Fatalln("Failed to create db and table, url:" + taosDSN + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to create stable meters, ErrMessage: " + err.Error()) } rowsAffected, err = res.RowsAffected() if err != nil { - log.Fatalln("Failed to get create db rowsAffected, url:" + taosDSN + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to get create stable rowsAffected, ErrMessage: " + err.Error()) } // you can check rowsAffected here fmt.Println("Create stable power.meters successfully, rowsAffected:", rowsAffected) @@ -53,20 +53,21 @@ func main() { "(NOW + 1a, 10.30000, 218, 0.25000) " res, err = db.Exec(insertQuery) if err != nil { - log.Fatal("Failed to insert data to power.meters, url:" + taosDSN + "; ErrMessage: " + err.Error()) + log.Fatal("Failed to insert data to power.meters, ErrMessage: " + err.Error()) } rowsAffected, err = res.RowsAffected() if err != nil { - log.Fatal("Failed to get insert rowsAffected, url:" + taosDSN + "; ErrMessage: " + err.Error()) + log.Fatal("Failed to get insert rowsAffected, ErrMessage: " + err.Error()) } // you can check affectedRows here fmt.Printf("Successfully inserted %d rows to power.meters.\n", rowsAffected) // ANCHOR_END: insert_data // ANCHOR: select_data // query data, make sure the database and table are created before - rows, err := db.Query("SELECT ts, current, location FROM power.meters limit 100") + sql := "SELECT ts, current, location FROM power.meters limit 100" + rows, err := db.Query(sql) if err != nil { - log.Fatal("Failed to query data from power.meters, url:" + taosDSN + "; ErrMessage: " + err.Error()) + log.Fatal("Failed to query data from power.meters, ErrMessage: " + err.Error()) } for rows.Next() { var ( @@ -76,7 +77,7 @@ func main() { ) err = rows.Scan(&ts, ¤t, &location) if err != nil { - log.Fatal("Failed to scan data, url:" + taosDSN + "; ErrMessage: " + err.Error()) + log.Fatal("Failed to scan data, sql:" + sql + ", ErrMessage: " + err.Error()) } // you can check data here fmt.Printf("ts: %s, current: %f, location: %s\n", ts, current, location) diff --git a/docs/examples/go/stmt/native/main.go b/docs/examples/go/stmt/native/main.go index 46db6eee46..c61cdba57e 100644 --- a/docs/examples/go/stmt/native/main.go +++ b/docs/examples/go/stmt/native/main.go @@ -23,22 +23,22 @@ func main() { // prepare database and table _, err = db.Exec("CREATE DATABASE IF NOT EXISTS power") if err != nil { - log.Fatalln("Failed to create db, host: " + host + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to create database power, ErrMessage: " + err.Error()) } _, err = db.Exec("USE power") if err != nil { - log.Fatalln("Failed to use db, host: " + host + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to use database power, ErrMessage: " + err.Error()) } _, err = db.Exec("CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))") if err != nil { - log.Fatalln("Failed to create table, host: " + host + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to create stable meters, ErrMessage: " + err.Error()) } // prepare statement sql := "INSERT INTO ? USING meters TAGS(?,?) VALUES (?,?,?,?)" stmt := db.Stmt() err = stmt.Prepare(sql) if err != nil { - log.Fatalln("Failed to prepare sql, host: " + host + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to prepare sql, sql: " + sql + ", ErrMessage: " + err.Error()) } for i := 1; i <= numOfSubTable; i++ { tableName := fmt.Sprintf("d_bind_%d", i) @@ -46,7 +46,7 @@ func main() { // set tableName and tags err = stmt.SetTableNameWithTags(tableName, tags) if err != nil { - log.Fatalln("Failed to set table name and tags, host: " + host + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to set table name and tags, tableName: " + tableName + "; ErrMessage: " + err.Error()) } // bind column data current := time.Now() @@ -58,18 +58,18 @@ func main() { AddFloat(rand.Float32()) err = stmt.BindRow(row) if err != nil { - log.Fatalln("Failed to bind params, host: " + host + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to bind params, ErrMessage: " + err.Error()) } } // add batch err = stmt.AddBatch() if err != nil { - log.Fatalln("Failed to add batch, host: " + host + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to add batch, ErrMessage: " + err.Error()) } // execute batch err = stmt.Execute() if err != nil { - log.Fatalln("Failed to exec, host: " + host + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to exec, ErrMessage: " + err.Error()) } // get affected rows affected := stmt.GetAffectedRows() diff --git a/docs/examples/go/stmt/ws/main.go b/docs/examples/go/stmt/ws/main.go index ae224c704f..289a2f1d57 100644 --- a/docs/examples/go/stmt/ws/main.go +++ b/docs/examples/go/stmt/ws/main.go @@ -27,11 +27,11 @@ func main() { // prepare database and table _, err = db.Exec("CREATE DATABASE IF NOT EXISTS power") if err != nil { - log.Fatalln("Failed to create db, url: " + taosDSN + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to create database power, ErrMessage: " + err.Error()) } _, err = db.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))") if err != nil { - log.Fatalln("Failed to create table, url: " + taosDSN + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to create stable power.meters, ErrMessage: " + err.Error()) } config := stmt.NewConfig(fmt.Sprintf("ws://%s:6041", host), 0) @@ -49,11 +49,11 @@ func main() { sql := "INSERT INTO ? USING meters TAGS(?,?) VALUES (?,?,?,?)" stmt, err := connector.Init() if err != nil { - log.Fatalln("Failed to init stmt, url: " + taosDSN + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to init stmt, sql: " + sql + ", ErrMessage: " + err.Error()) } err = stmt.Prepare(sql) if err != nil { - log.Fatal("Failed to prepare sql, url: " + taosDSN + "; ErrMessage: " + err.Error()) + log.Fatal("Failed to prepare sql, sql: " + sql + ", ErrMessage: " + err.Error()) } for i := 1; i <= numOfSubTable; i++ { tableName := fmt.Sprintf("d_bind_%d", i) @@ -63,12 +63,12 @@ func main() { // set tableName err = stmt.SetTableName(tableName) if err != nil { - log.Fatal("Failed to set table name, url: " + taosDSN + "; ErrMessage: " + err.Error()) + log.Fatal("Failed to set table name, tableName: " + tableName + "; ErrMessage: " + err.Error()) } // set tags err = stmt.SetTags(tags, tagsType) if err != nil { - log.Fatal("Failed to set tags, url: " + taosDSN + "; ErrMessage: " + err.Error()) + log.Fatal("Failed to set tags, ErrMessage: " + err.Error()) } // bind column data current := time.Now() @@ -80,18 +80,18 @@ func main() { columnData[3] = param.NewParam(1).AddFloat(rand.Float32()) err = stmt.BindParam(columnData, columnType) if err != nil { - log.Fatal("Failed to bind params, url: " + taosDSN + "; ErrMessage: " + err.Error()) + log.Fatal("Failed to bind params, ErrMessage: " + err.Error()) } } // add batch err = stmt.AddBatch() if err != nil { - log.Fatal("Failed to add batch, url: " + taosDSN + "; ErrMessage: " + err.Error()) + log.Fatal("Failed to add batch, ErrMessage: " + err.Error()) } // execute batch err = stmt.Exec() if err != nil { - log.Fatal("Failed to exec, url: " + taosDSN + "; ErrMessage: " + err.Error()) + log.Fatal("Failed to exec, ErrMessage: " + err.Error()) } // get affected rows affected := stmt.GetAffectedRows() @@ -100,6 +100,6 @@ func main() { } err = stmt.Close() if err != nil { - log.Fatal("Failed to close stmt, url: " + taosDSN + "; ErrMessage: " + err.Error()) + log.Fatal("Failed to close stmt, ErrMessage: " + err.Error()) } } diff --git a/docs/examples/go/tmq/native/main.go b/docs/examples/go/tmq/native/main.go index 4bf2fb4a60..638a07d235 100644 --- a/docs/examples/go/tmq/native/main.go +++ b/docs/examples/go/tmq/native/main.go @@ -48,7 +48,7 @@ func main() { // ANCHOR: subscribe err = consumer.Subscribe("topic_meters", nil) if err != nil { - log.Fatalln("Failed to subscribe, host : " + host + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to subscribe topic_meters, ErrMessage: " + err.Error()) } log.Println("Subscribe topics successfully") for i := 0; i < 50; i++ { @@ -62,13 +62,13 @@ func main() { // commit offset _, err = consumer.CommitOffsets([]tmqcommon.TopicPartition{e.TopicPartition}) if err != nil { - log.Fatalln("Failed to commit offset, host : " + host + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to commit offset, ErrMessage: " + err.Error()) } log.Println("Commit offset manually successfully.") // ANCHOR_END: commit_offset case tmqcommon.Error: fmt.Printf("%% Error: %v: %v\n", e.Code(), e) - log.Fatalln("Failed to poll data, host : " + host + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to poll data, ErrMessage: " + err.Error()) } } } @@ -77,7 +77,7 @@ func main() { // get assignment partitions, err := consumer.Assignment() if err != nil { - log.Fatal("Failed to get assignment; ErrMessage: " + err.Error()) + log.Fatal("Failed to get assignment, ErrMessage: " + err.Error()) } fmt.Println("Now assignment:", partitions) for i := 0; i < len(partitions); i++ { @@ -88,7 +88,7 @@ func main() { Offset: 0, }, 0) if err != nil { - log.Fatalln("Seek example failed; ErrMessage: " + err.Error()) + log.Fatalln("Failed to execute seek example, ErrMessage: " + err.Error()) } } fmt.Println("Assignment seek to beginning successfully") @@ -97,13 +97,15 @@ func main() { // unsubscribe err = consumer.Unsubscribe() if err != nil { - log.Fatal("Failed to unsubscribe consumer. ErrMessage: " + err.Error()) + log.Fatal("Failed to unsubscribe consumer, ErrMessage: " + err.Error()) } + fmt.Println("Consumer unsubscribed successfully.") // close consumer err = consumer.Close() if err != nil { - log.Fatal("Failed to close consumer. ErrMessage: " + err.Error()) + log.Fatal("Failed to close consumer, ErrMessage: " + err.Error()) } + fmt.Println("Consumer closed successfully.") // ANCHOR_END: close <-done } @@ -111,22 +113,22 @@ func main() { func initEnv(conn *sql.DB) { _, err := conn.Exec("CREATE DATABASE IF NOT EXISTS power") if err != nil { - log.Fatal("Failed to create database. ErrMessage: " + err.Error()) + log.Fatal("Failed to create database, ErrMessage: " + err.Error()) } _, err = conn.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))") if err != nil { - log.Fatal("Failed to create stable. ErrMessage: " + err.Error()) + log.Fatal("Failed to create stable, ErrMessage: " + err.Error()) } _, err = conn.Exec("CREATE TOPIC IF NOT EXISTS topic_meters AS SELECT ts, current, voltage, phase, groupid, location FROM power.meters") if err != nil { - log.Fatal("Failed to create topic. ErrMessage: " + err.Error()) + log.Fatal("Failed to create topic, ErrMessage: " + err.Error()) } go func() { for i := 0; i < 10; i++ { time.Sleep(time.Second) _, err = conn.Exec("INSERT INTO power.d1001 USING power.meters TAGS (2, 'California.SanFrancisco') VALUES (NOW , 10.2, 219, 0.32)") if err != nil { - log.Fatal("Failed to insert data. ErrMessage: " + err.Error()) + log.Fatal("Failed to insert data, ErrMessage: " + err.Error()) } } done <- struct{}{} diff --git a/docs/examples/go/tmq/ws/main.go b/docs/examples/go/tmq/ws/main.go index c6be0326b5..70ea3af0b3 100644 --- a/docs/examples/go/tmq/ws/main.go +++ b/docs/examples/go/tmq/ws/main.go @@ -53,7 +53,7 @@ func main() { // ANCHOR: subscribe err = consumer.Subscribe("topic_meters", nil) if err != nil { - log.Fatalln("Failed to subscribe, host : " + wsUrl + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to subscribe topic_meters, ErrMessage: " + err.Error()) } log.Println("Subscribe topics successfully") for i := 0; i < 50; i++ { @@ -67,13 +67,13 @@ func main() { // commit offset _, err = consumer.CommitOffsets([]tmqcommon.TopicPartition{e.TopicPartition}) if err != nil { - log.Fatalln("Failed to commit offset, host : " + wsUrl + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to commit offset, ErrMessage: " + err.Error()) } log.Println("Commit offset manually successfully.") // ANCHOR_END: commit_offset case tmqcommon.Error: fmt.Printf("%% Error: %v: %v\n", e.Code(), e) - log.Fatalln("Failed to poll data, host : " + wsUrl + "; ErrMessage: " + err.Error()) + log.Fatalln("Failed to poll data, ErrMessage: " + err.Error()) } } } @@ -82,7 +82,7 @@ func main() { // get assignment partitions, err := consumer.Assignment() if err != nil { - log.Fatal("Failed to get assignment; ErrMessage: " + err.Error()) + log.Fatal("Failed to get assignment, ErrMessage: " + err.Error()) } fmt.Println("Now assignment:", partitions) for i := 0; i < len(partitions); i++ { @@ -93,7 +93,7 @@ func main() { Offset: 0, }, 0) if err != nil { - log.Fatalln("Seek example failed; ErrMessage: " + err.Error()) + log.Fatalln("Failed to execute seek example, ErrMessage: " + err.Error()) } } fmt.Println("Assignment seek to beginning successfully") @@ -102,13 +102,15 @@ func main() { // unsubscribe err = consumer.Unsubscribe() if err != nil { - log.Fatal("Failed to unsubscribe consumer. ErrMessage: " + err.Error()) + log.Fatal("Failed to unsubscribe consumer, ErrMessage: " + err.Error()) } + fmt.Println("Consumer unsubscribed successfully.") // close consumer err = consumer.Close() if err != nil { - log.Fatal("Failed to close consumer. ErrMessage: " + err.Error()) + log.Fatal("Failed to close consumer, ErrMessage: " + err.Error()) } + fmt.Println("Consumer closed successfully.") // ANCHOR_END: close <-done } @@ -116,22 +118,22 @@ func main() { func initEnv(conn *sql.DB) { _, err := conn.Exec("CREATE DATABASE IF NOT EXISTS power") if err != nil { - log.Fatal("Failed to create database. ErrMessage: " + err.Error()) + log.Fatal("Failed to create database, ErrMessage: " + err.Error()) } _, err = conn.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))") if err != nil { - log.Fatal("Failed to create stable. ErrMessage: " + err.Error()) + log.Fatal("Failed to create stable, ErrMessage: " + err.Error()) } _, err = conn.Exec("CREATE TOPIC IF NOT EXISTS topic_meters AS SELECT ts, current, voltage, phase, groupid, location FROM power.meters") if err != nil { - log.Fatal("Failed to create topic. ErrMessage: " + err.Error()) + log.Fatal("Failed to create topic, ErrMessage: " + err.Error()) } go func() { for i := 0; i < 10; i++ { time.Sleep(time.Second) _, err = conn.Exec("INSERT INTO power.d1001 USING power.meters TAGS (2, 'California.SanFrancisco') VALUES (NOW , 10.2, 219, 0.32)") if err != nil { - log.Fatal("Failed to insert data. ErrMessage: " + err.Error()) + log.Fatal("Failed to insert data, ErrMessage: " + err.Error()) } } done <- struct{}{} diff --git a/docs/examples/java/pom.xml b/docs/examples/java/pom.xml index e7969bd4eb..35fe5f280c 100644 --- a/docs/examples/java/pom.xml +++ b/docs/examples/java/pom.xml @@ -25,6 +25,24 @@ 3.3.0 + + + + com.alibaba + druid + 1.1.17 + + + + com.zaxxer + HikariCP + 3.2.0 + + + org.locationtech.jts + jts-core + 1.19.0 + junit junit diff --git a/docs/examples/java/src/main/java/com/taos/example/ConsumerLoopFull.java b/docs/examples/java/src/main/java/com/taos/example/ConsumerLoopFull.java new file mode 100644 index 0000000000..62dac019d7 --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/ConsumerLoopFull.java @@ -0,0 +1,384 @@ +package com.taos.example; + +import com.alibaba.fastjson.JSON; +import com.taosdata.jdbc.TSDBDriver; +import com.taosdata.jdbc.tmq.*; + +import java.sql.*; +import java.time.Duration; +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +// ANCHOR: consumer_demo +public class ConsumerLoopFull { + static private Connection connection; + static private Statement statement; + static private volatile boolean stopThread = false; + + public static TaosConsumer getConsumer() throws Exception { +// ANCHOR: create_consumer + Properties config = new Properties(); + config.setProperty("td.connect.type", "jni"); + config.setProperty("bootstrap.servers", "localhost:6030"); + config.setProperty("auto.offset.reset", "latest"); + config.setProperty("msg.with.table.name", "true"); + config.setProperty("enable.auto.commit", "true"); + config.setProperty("auto.commit.interval.ms", "1000"); + config.setProperty("group.id", "group1"); + config.setProperty("client.id", "1"); + config.setProperty("td.connect.user", "root"); + config.setProperty("td.connect.pass", "taosdata"); + config.setProperty("value.deserializer", "com.taos.example.ConsumerLoopFull$ResultDeserializer"); + config.setProperty("value.deserializer.encoding", "UTF-8"); + + try { + TaosConsumer consumer= new TaosConsumer<>(config); + System.out.printf("Create consumer successfully, host: %s, groupId: %s, clientId: %s%n", + config.getProperty("bootstrap.servers"), + config.getProperty("group.id"), + config.getProperty("client.id")); + return consumer; + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to create native consumer, host: %s, %sErrMessage: %s%n", + config.getProperty("bootstrap.servers"), + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; + } +// ANCHOR_END: create_consumer + } + + public static void pollExample(TaosConsumer consumer) throws SQLException { +// ANCHOR: poll_data_code_piece + try { + List topics = Collections.singletonList("topic_meters"); + + // subscribe to the topics + consumer.subscribe(topics); + System.out.println("Subscribe topics successfully."); + for (int i = 0; i < 50; i++) { + // poll data + ConsumerRecords records = consumer.poll(Duration.ofMillis(100)); + for (ConsumerRecord record : records) { + ResultBean bean = record.value(); + // process the data here + System.out.println("data: " + JSON.toJSONString(bean)); + } + } + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to poll data, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; + } +// ANCHOR_END: poll_data_code_piece + } + + public static void seekExample(TaosConsumer consumer) throws SQLException { +// ANCHOR: consumer_seek + try { + List topics = Collections.singletonList("topic_meters"); + + // subscribe to the topics + consumer.subscribe(topics); + System.out.println("Subscribe topics successfully."); + Set assignment = consumer.assignment(); + System.out.println("Now assignment: " + JSON.toJSONString(assignment)); + + ConsumerRecords records = ConsumerRecords.emptyRecord(); + // make sure we have got some data + while (records.isEmpty()) { + records = consumer.poll(Duration.ofMillis(100)); + } + + consumer.seekToBeginning(assignment); + System.out.println("Assignment seek to beginning successfully."); + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to execute seek example, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; + } +// ANCHOR_END: consumer_seek + } + + + public static void commitExample(TaosConsumer consumer) throws SQLException { +// ANCHOR: commit_code_piece + try { + List topics = Collections.singletonList("topic_meters"); + + consumer.subscribe(topics); + for (int i = 0; i < 50; i++) { + ConsumerRecords records = consumer.poll(Duration.ofMillis(100)); + for (ConsumerRecord record : records) { + ResultBean bean = record.value(); + // process your data here + System.out.println("data: " + JSON.toJSONString(bean)); + } + if (!records.isEmpty()) { + // after processing the data, commit the offset manually + consumer.commitSync(); + System.out.println("Commit offset manually successfully."); + } + } + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to execute commit example, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; + } +// ANCHOR_END: commit_code_piece + } + + public static void unsubscribeExample(TaosConsumer consumer) throws SQLException { + List topics = Collections.singletonList("topic_meters"); + consumer.subscribe(topics); +// ANCHOR: unsubscribe_data_code_piece + try { + // unsubscribe the consumer + consumer.unsubscribe(); + System.out.println("Consumer unsubscribed successfully."); + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to unsubscribe consumer, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; + } + finally { + // close the consumer + consumer.close(); + System.out.println("Consumer closed successfully."); + } +// ANCHOR_END: unsubscribe_data_code_piece + } + + public static class ResultDeserializer extends ReferenceDeserializer { + + } + + // use this class to define the data structure of the result record + public static class ResultBean { + private Timestamp ts; + private double current; + private int voltage; + private double phase; + private int groupid; + private String location; + + public Timestamp getTs() { + return ts; + } + + public void setTs(Timestamp ts) { + this.ts = ts; + } + + public double getCurrent() { + return current; + } + + public void setCurrent(double current) { + this.current = current; + } + + public int getVoltage() { + return voltage; + } + + public void setVoltage(int voltage) { + this.voltage = voltage; + } + + public double getPhase() { + return phase; + } + + public void setPhase(double phase) { + this.phase = phase; + } + + public int getGroupid() { + return groupid; + } + + public void setGroupid(int groupid) { + this.groupid = groupid; + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + } + + public static void prepareData() throws SQLException, InterruptedException { + try { + int i = 0; + while (!stopThread) { + String insertQuery = "INSERT INTO power.d1001 USING power.meters TAGS(2,'California.SanFrancisco') VALUES (NOW + " + i + "a, 10.30000, 219, 0.31000) "; + int affectedRows = statement.executeUpdate(insertQuery); + assert affectedRows == 1; + i++; + Thread.sleep(1); + } + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to insert data to power.meters, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; + } + } + + public static void prepareMeta() throws SQLException { + try { + statement.executeUpdate("CREATE DATABASE IF NOT EXISTS power"); + statement.executeUpdate("USE power"); + statement.executeUpdate("CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))"); + statement.executeUpdate("CREATE TOPIC IF NOT EXISTS topic_meters AS SELECT ts, current, voltage, phase, groupid, location FROM meters"); + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to create db and table, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; + } + } + + public static void initConnection() throws SQLException { + String url = "jdbc:TAOS://localhost:6030?user=root&password=taosdata"; + Properties properties = new Properties(); + properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "C"); + properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); + + try { + connection = DriverManager.getConnection(url, properties); + } catch (SQLException ex) { + System.out.println("Failed to create connection, url:" + url + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); + throw new SQLException("Failed to create connection", ex); + } + try { + statement = connection.createStatement(); + } catch (SQLException ex) { + System.out.println("Failed to create statement, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); + throw new SQLException("Failed to create statement", ex); + } + System.out.println("Connection created successfully."); + } + + public static void closeConnection() throws SQLException { + try { + if (statement != null) { + statement.close(); + } + } catch (SQLException ex) { + System.out.println("Failed to close statement, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); + throw new SQLException("Failed to close statement", ex); + } + + try { + if (connection != null) { + connection.close(); + } + } catch (SQLException ex) { + System.out.println("Failed to close connection, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); + throw new SQLException("Failed to close connection", ex); + } + System.out.println("Connection closed Successfully."); + } + + + public static void main(String[] args) throws SQLException, InterruptedException { + initConnection(); + prepareMeta(); + + // create a single thread executor + ExecutorService executor = Executors.newSingleThreadExecutor(); + + // submit a task + executor.submit(() -> { + try { + prepareData(); + } catch (SQLException ex) { + System.out.println("Failed to prepare data, ErrCode:" + ex.getErrorCode() + ", ErrMessage: " + ex.getMessage()); + return; + } catch (Exception ex) { + System.out.println("Failed to prepare data, ErrMessage: " + ex.getMessage()); + return; + } + System.out.println("pollDataExample executed successfully."); + }); + + try { + TaosConsumer consumer = getConsumer(); + + pollExample(consumer); + System.out.println("pollExample executed successfully."); + consumer.unsubscribe(); + + seekExample(consumer); + System.out.println("seekExample executed successfully."); + consumer.unsubscribe(); + + commitExample(consumer); + System.out.println("commitExample executed successfully."); + consumer.unsubscribe(); + + unsubscribeExample(consumer); + System.out.println("unsubscribeExample executed successfully"); + } catch (SQLException ex) { + System.out.println("Failed to poll data from topic_meters, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); + return; + } catch (Exception ex) { + System.out.println("Failed to poll data from topic_meters, ErrMessage: " + ex.getMessage()); + return; + } + + stopThread = true; + // close the executor, which will make the executor reject new tasks + executor.shutdown(); + + try { + // wait for the executor to terminate + boolean result = executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); + assert result; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Wait executor termination failed."); + } + + closeConnection(); + System.out.println("program end."); + } +} +// ANCHOR_END: consumer_demo diff --git a/docs/examples/java/src/main/java/com/taos/example/DruidDemo.java b/docs/examples/java/src/main/java/com/taos/example/DruidDemo.java new file mode 100644 index 0000000000..a366efd419 --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/DruidDemo.java @@ -0,0 +1,36 @@ +package com.taosdata.example; + +import com.alibaba.druid.pool.DruidDataSource; + +import java.sql.Connection; +import java.sql.Statement; + +public class DruidDemo { + // ANCHOR: connection_pool + public static void main(String[] args) throws Exception { + String url = "jdbc:TAOS://127.0.0.1:6030/log"; + + DruidDataSource dataSource = new DruidDataSource(); + // jdbc properties + dataSource.setDriverClassName("com.taosdata.jdbc.TSDBDriver"); + dataSource.setUrl(url); + dataSource.setUsername("root"); + dataSource.setPassword("taosdata"); + // pool configurations + dataSource.setInitialSize(10); + dataSource.setMinIdle(10); + dataSource.setMaxActive(10); + dataSource.setMaxWait(30000); + dataSource.setValidationQuery("SELECT SERVER_VERSION()"); + + Connection connection = dataSource.getConnection(); // get connection + Statement statement = connection.createStatement(); // get statement + // query or insert + // ... + + statement.close(); + connection.close(); // put back to connection pool + dataSource.close(); + } + // ANCHOR_END: connection_pool +} diff --git a/docs/examples/java/src/main/java/com/taos/example/GeometryDemo.java b/docs/examples/java/src/main/java/com/taos/example/GeometryDemo.java new file mode 100644 index 0000000000..036125e7ea --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/GeometryDemo.java @@ -0,0 +1,190 @@ +package com.taos.example; + +import com.taosdata.jdbc.TSDBPreparedStatement; +import org.locationtech.jts.geom.*; +import org.locationtech.jts.io.ByteOrderValues; +import org.locationtech.jts.io.ParseException; +import org.locationtech.jts.io.WKBReader; +import org.locationtech.jts.io.WKBWriter; + +import java.sql.*; +import java.util.ArrayList; +import java.util.Properties; + +public class GeometryDemo { + private static String host = "localhost"; + private static final String dbName = "test"; + private static final String tbName = "weather"; + private static final String user = "root"; + private static final String password = "taosdata"; + + private Connection connection; + + public static void main(String[] args) throws SQLException { + for (int i = 0; i < args.length; i++) { + if ("-host".equalsIgnoreCase(args[i]) && i < args.length - 1) + host = args[++i]; + } + if (host == null) { + printHelp(); + } + GeometryDemo demo = new GeometryDemo(); + demo.init(); + demo.createDatabase(); + demo.useDatabase(); + demo.dropTable(); + demo.createTable(); + + demo.insert(); + demo.stmtInsert(); + demo.select(); + + demo.dropTable(); + demo.close(); + } + + private void init() { + final String url = "jdbc:TAOS://" + host + ":6030/?user=" + user + "&password=" + password; + // get connection + try { + Properties properties = new Properties(); + properties.setProperty("charset", "UTF-8"); + properties.setProperty("locale", "en_US.UTF-8"); + properties.setProperty("timezone", "UTC-8"); + System.out.println("get connection starting..."); + connection = DriverManager.getConnection(url, properties); + if (connection != null) + System.out.println("[ OK ] Connection established."); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + private void createDatabase() { + String sql = "create database if not exists " + dbName; + execute(sql); + } + + private void useDatabase() { + String sql = "use " + dbName; + execute(sql); + } + + private void dropTable() { + final String sql = "drop table if exists " + dbName + "." + tbName + ""; + execute(sql); + } + + private void createTable() { + final String sql = "create table if not exists " + dbName + "." + tbName + " (ts timestamp, temperature float, humidity int, location geometry(50))"; + execute(sql); + } + + private void insert() { + final String sql = "insert into " + dbName + "." + tbName + " (ts, temperature, humidity, location) values(now, 20.5, 34, 'POINT(1 2)')"; + execute(sql); + } + + private void stmtInsert() throws SQLException { + TSDBPreparedStatement preparedStatement = (TSDBPreparedStatement) connection.prepareStatement("insert into " + dbName + "." + tbName + " values (?, ?, ?, ?)"); + + long current = System.currentTimeMillis(); + ArrayList tsList = new ArrayList<>(); + tsList.add(current); + tsList.add(current + 1); + preparedStatement.setTimestamp(0, tsList); + ArrayList tempList = new ArrayList<>(); + tempList.add(20.1F); + tempList.add(21.2F); + preparedStatement.setFloat(1, tempList); + ArrayList humList = new ArrayList<>(); + humList.add(30); + humList.add(31); + preparedStatement.setInt(2, humList); + + + ArrayList list = new ArrayList<>(); + GeometryFactory gf = new GeometryFactory(); + Point p1 = gf.createPoint(new Coordinate(1,2)); + p1.setSRID(1234); + + // NOTE: TDengine current version only support 2D dimension and little endian byte order + WKBWriter w = new WKBWriter(2, ByteOrderValues.LITTLE_ENDIAN, true); + byte[] wkb = w.write(p1); + list.add(wkb); + + Coordinate[] coordinates = { new Coordinate(10, 20), + new Coordinate(30, 40)}; + LineString lineString = gf.createLineString(coordinates); + lineString.setSRID(2345); + byte[] wkb2 = w.write(lineString); + list.add(wkb2); + + preparedStatement.setGeometry(3, list, 50); + + preparedStatement.columnDataAddBatch(); + preparedStatement.columnDataExecuteBatch(); + } + + private void select() { + final String sql = "select * from " + dbName + "." + tbName; + executeQuery(sql); + } + + private void close() { + try { + if (connection != null) { + this.connection.close(); + System.out.println("connection closed."); + } + } catch (SQLException e) { + e.printStackTrace(); + } + } + + private void executeQuery(String sql) { + long start = System.currentTimeMillis(); + try (Statement statement = connection.createStatement()) { + ResultSet resultSet = statement.executeQuery(sql); + long end = System.currentTimeMillis(); + printSql(sql, true, (end - start)); + + while (resultSet.next()){ + byte[] result1 = resultSet.getBytes(4); + WKBReader reader = new WKBReader(); + Geometry g1 = reader.read(result1); + System.out.println("GEO OBJ: " + g1 + ", SRID: " + g1.getSRID()); + } + + } catch (SQLException e) { + long end = System.currentTimeMillis(); + printSql(sql, false, (end - start)); + e.printStackTrace(); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + private void printSql(String sql, boolean succeed, long cost) { + System.out.println("[ " + (succeed ? "OK" : "ERROR!") + " ] time cost: " + cost + " ms, execute statement ====> " + sql); + } + + private void execute(String sql) { + long start = System.currentTimeMillis(); + try (Statement statement = connection.createStatement()) { + boolean execute = statement.execute(sql); + long end = System.currentTimeMillis(); + printSql(sql, true, (end - start)); + } catch (SQLException e) { + long end = System.currentTimeMillis(); + printSql(sql, false, (end - start)); + e.printStackTrace(); + } + } + + private static void printHelp() { + System.out.println("Usage: java -jar JDBCDemo.jar -host "); + System.exit(0); + } + +} diff --git a/docs/examples/java/src/main/java/com/taos/example/HikariDemo.java b/docs/examples/java/src/main/java/com/taos/example/HikariDemo.java new file mode 100644 index 0000000000..50b20fdb0c --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/HikariDemo.java @@ -0,0 +1,37 @@ +package com.taosdata.example; + +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; + +import java.sql.Connection; +import java.sql.Statement; + +public class HikariDemo { + // ANCHOR: connection_pool + public static void main(String[] args) throws Exception { + HikariConfig config = new HikariConfig(); + // jdbc properties + config.setJdbcUrl("jdbc:TAOS://127.0.0.1:6030/log"); + config.setUsername("root"); + config.setPassword("taosdata"); + // connection pool configurations + config.setMinimumIdle(10); // minimum number of idle connection + config.setMaximumPoolSize(10); // maximum number of connection in the pool + config.setConnectionTimeout(30000); // maximum wait milliseconds for get connection from pool + config.setMaxLifetime(0); // maximum life time for each connection + config.setIdleTimeout(0); // max idle time for recycle idle connection + config.setConnectionTestQuery("SELECT SERVER_VERSION()"); // validation query + + HikariDataSource dataSource = new HikariDataSource(config); // create datasource + + Connection connection = dataSource.getConnection(); // get connection + Statement statement = connection.createStatement(); // get statement + + // query or insert + // ... + statement.close(); + connection.close(); // put back to connection pool + dataSource.close(); + } + // ANCHOR_END: connection_pool +} diff --git a/docs/examples/java/src/main/java/com/taos/example/JNIConnectExample.java b/docs/examples/java/src/main/java/com/taos/example/JNIConnectExample.java index 42ac7bde85..4950654cf6 100644 --- a/docs/examples/java/src/main/java/com/taos/example/JNIConnectExample.java +++ b/docs/examples/java/src/main/java/com/taos/example/JNIConnectExample.java @@ -8,31 +8,33 @@ import java.util.Properties; import com.taosdata.jdbc.TSDBDriver; public class JNIConnectExample { -// ANCHOR: main -public static void main(String[] args) throws SQLException { - // use - // String jdbcUrl = "jdbc:TAOS://localhost:6030/dbName?user=root&password=taosdata"; - // if you want to connect a specified database named "dbName". - String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata"; - Properties connProps = new Properties(); - connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); - connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); + // ANCHOR: main + public static void main(String[] args) throws Exception { + // use + // String jdbcUrl = + // "jdbc:TAOS://localhost:6030/dbName?user=root&password=taosdata"; + // if you want to connect a specified database named "dbName". + String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata"; + Properties connProps = new Properties(); + connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); + connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); + connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); - try (Connection conn = DriverManager.getConnection(jdbcUrl, connProps)) { - System.out.println("Connected to " + jdbcUrl + " successfully."); + try (Connection conn = DriverManager.getConnection(jdbcUrl, connProps)) { + System.out.println("Connected to " + jdbcUrl + " successfully."); - // you can use the connection for execute SQL here + // you can use the connection for execute SQL here - } catch (SQLException ex) { - // handle any errors, please refer to the JDBC specifications for detailed exceptions info - System.out.println("Failed to connect to " + jdbcUrl + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw ex; - } catch (Exception ex){ - System.out.println("Failed to connect to " + jdbcUrl + "; ErrMessage: " + ex.getMessage()); - throw ex; + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to connect to %s, %sErrMessage: %s%n", + jdbcUrl, + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; + } } + // ANCHOR_END: main } -// ANCHOR_END: main -} - diff --git a/docs/examples/java/src/main/java/com/taos/example/JdbcBasicDemo.java b/docs/examples/java/src/main/java/com/taos/example/JdbcBasicDemo.java new file mode 100644 index 0000000000..f9b30f52d9 --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/JdbcBasicDemo.java @@ -0,0 +1,125 @@ +package com.taos.example; + +import com.taosdata.jdbc.AbstractStatement; + +import java.sql.*; +import java.util.Properties; + +public class JdbcBasicDemo { + private static final String host = "localhost"; + private static final String dbName = "test"; + private static final String tbName = "weather"; + private static final String user = "root"; + private static final String password = "taosdata"; + + + public static void main(String[] args) throws SQLException { + + final String url = "jdbc:TAOS://" + host + ":6030/?user=" + user + "&password=" + password; + +// get connection + Properties properties = new Properties(); + properties.setProperty("charset", "UTF-8"); + properties.setProperty("locale", "en_US.UTF-8"); + properties.setProperty("timezone", "UTC-8"); + System.out.println("get connection starting..."); + try (Connection connection = DriverManager.getConnection(url, properties)) { + + + if (connection != null) { + System.out.println("[ OK ] Connection established."); + } else { + System.out.println("[ ERR ] Connection can not be established."); + return; + } + + Statement stmt = connection.createStatement(); + +// ANCHOR: create_db_and_table +// create database + stmt.executeUpdate("CREATE DATABASE IF NOT EXISTS power"); + +// use database + stmt.executeUpdate("USE power"); + +// create table + stmt.executeUpdate("CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))"); +// ANCHOR_END: create_db_and_table + +// ANCHOR: insert_data +// insert data + String insertQuery = "INSERT INTO " + + "power.d1001 USING power.meters TAGS(2,'California.SanFrancisco') " + + "VALUES " + + "(NOW + 1a, 10.30000, 219, 0.31000) " + + "(NOW + 2a, 12.60000, 218, 0.33000) " + + "(NOW + 3a, 12.30000, 221, 0.31000) " + + "power.d1002 USING power.meters TAGS(3, 'California.SanFrancisco') " + + "VALUES " + + "(NOW + 1a, 10.30000, 218, 0.25000) "; + int affectedRows = stmt.executeUpdate(insertQuery); + System.out.println("insert " + affectedRows + " rows."); +// ANCHOR_END: insert_data + + +// ANCHOR: query_data +// query data + ResultSet resultSet = stmt.executeQuery("SELECT * FROM meters"); + + Timestamp ts; + float current; + String location; + while (resultSet.next()) { + ts = resultSet.getTimestamp(1); + current = resultSet.getFloat(2); + location = resultSet.getString("location"); + + System.out.printf("%s, %f, %s\n", ts, current, location); + } +// ANCHOR_END: query_data + +// ANCHOR: with_reqid + AbstractStatement aStmt = (AbstractStatement) connection.createStatement(); + aStmt.execute("CREATE DATABASE IF NOT EXISTS power", 1L); + aStmt.executeUpdate("USE power", 2L); + try (ResultSet rs = aStmt.executeQuery("SELECT * FROM meters limit 1", 3L)) { + while (rs.next()) { + Timestamp timestamp = rs.getTimestamp(1); + System.out.println("timestamp = " + timestamp); + } + } + aStmt.close(); +// ANCHOR_END: with_reqid + + + String sql = "SELECT * FROM meters limit 2;"; + +// ANCHOR: jdbc_exception + try (Statement statement = connection.createStatement(); + // executeQuery + ResultSet tempResultSet = statement.executeQuery(sql)) { + + // print result + printResult(tempResultSet); + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to execute statement, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; + } +// ANCHOR_END: jdbc_exception + } catch (SQLException ex) { + // handle any errors, please refer to the JDBC specifications for detailed exceptions info + System.out.println("Error Code: " + ex.getErrorCode()); + System.out.println("Message: " + ex.getMessage()); + } + } + + private static void printResult(ResultSet resultSet) throws SQLException { + Util.printResult(resultSet); + } + +} diff --git a/docs/examples/java/src/main/java/com/taos/example/JdbcCreatDBDemo.java b/docs/examples/java/src/main/java/com/taos/example/JdbcCreatDBDemo.java new file mode 100644 index 0000000000..0293f15b53 --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/JdbcCreatDBDemo.java @@ -0,0 +1,53 @@ +package com.taos.example; + +import java.sql.*; +import java.util.Properties; + +public class JdbcCreatDBDemo { + private static final String host = "localhost"; + private static final String dbName = "test"; + private static final String tbName = "weather"; + private static final String user = "root"; + private static final String password = "taosdata"; + + + public static void main(String[] args) throws SQLException { + + final String jdbcUrl = "jdbc:TAOS://" + host + ":6030/?user=" + user + "&password=" + password; + +// get connection + Properties properties = new Properties(); + properties.setProperty("charset", "UTF-8"); + properties.setProperty("locale", "en_US.UTF-8"); + properties.setProperty("timezone", "UTC-8"); + System.out.println("get connection starting..."); +// ANCHOR: create_db_and_table + try (Connection connection = DriverManager.getConnection(jdbcUrl, properties); + Statement stmt = connection.createStatement()) { + + // create database + int rowsAffected = stmt.executeUpdate("CREATE DATABASE IF NOT EXISTS power"); + // you can check rowsAffected here + System.out.println("Create database power successfully, rowsAffected: " + rowsAffected); + // create table + rowsAffected = stmt.executeUpdate("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))"); + // you can check rowsAffected here + System.out.println("Create stable power.meters successfully, rowsAffected: " + rowsAffected); + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to create database power or stable meters, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; + } +// ANCHOR_END: create_db_and_table + + } + + private static void printResult(ResultSet resultSet) throws SQLException { + Util.printResult(resultSet); + } + +} diff --git a/docs/examples/java/src/main/java/com/taos/example/JdbcInsertDataDemo.java b/docs/examples/java/src/main/java/com/taos/example/JdbcInsertDataDemo.java new file mode 100644 index 0000000000..f19017193c --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/JdbcInsertDataDemo.java @@ -0,0 +1,55 @@ +package com.taos.example; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Properties; + +public class JdbcInsertDataDemo { + private static final String host = "localhost"; + private static final String dbName = "test"; + private static final String tbName = "weather"; + private static final String user = "root"; + private static final String password = "taosdata"; + + + public static void main(String[] args) throws SQLException { + + final String jdbcUrl = "jdbc:TAOS://" + host + ":6030/?user=" + user + "&password=" + password; + +// get connection + Properties properties = new Properties(); + properties.setProperty("charset", "UTF-8"); + properties.setProperty("locale", "en_US.UTF-8"); + properties.setProperty("timezone", "UTC-8"); + System.out.println("get connection starting..."); +// ANCHOR: insert_data + try (Connection connection = DriverManager.getConnection(jdbcUrl, properties); + Statement stmt = connection.createStatement()) { + + // insert data, please make sure the database and table are created before + String insertQuery = "INSERT INTO " + + "power.d1001 USING power.meters TAGS(2,'California.SanFrancisco') " + + "VALUES " + + "(NOW + 1a, 10.30000, 219, 0.31000) " + + "(NOW + 2a, 12.60000, 218, 0.33000) " + + "(NOW + 3a, 12.30000, 221, 0.31000) " + + "power.d1002 USING power.meters TAGS(3, 'California.SanFrancisco') " + + "VALUES " + + "(NOW + 1a, 10.30000, 218, 0.25000) "; + int affectedRows = stmt.executeUpdate(insertQuery); + // you can check affectedRows here + System.out.println("Successfully inserted " + affectedRows + " rows to power.meters."); + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to insert data to power.meters, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; + } +// ANCHOR_END: insert_data + } +} diff --git a/docs/examples/java/src/main/java/com/taos/example/JdbcQueryDemo.java b/docs/examples/java/src/main/java/com/taos/example/JdbcQueryDemo.java new file mode 100644 index 0000000000..4b28a7de28 --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/JdbcQueryDemo.java @@ -0,0 +1,55 @@ +package com.taos.example; + +import java.sql.*; +import java.util.Properties; + +public class JdbcQueryDemo { + private static final String host = "localhost"; + private static final String dbName = "test"; + private static final String tbName = "weather"; + private static final String user = "root"; + private static final String password = "taosdata"; + + + public static void main(String[] args) throws SQLException { + + final String jdbcUrl = "jdbc:TAOS://" + host + ":6030/?user=" + user + "&password=" + password; + +// get connection + Properties properties = new Properties(); + properties.setProperty("charset", "UTF-8"); + properties.setProperty("locale", "en_US.UTF-8"); + properties.setProperty("timezone", "UTC-8"); + System.out.println("get connection starting..."); +// ANCHOR: query_data + String sql = "SELECT ts, current, location FROM power.meters limit 100"; + try (Connection connection = DriverManager.getConnection(jdbcUrl, properties); + Statement stmt = connection.createStatement(); + // query data, make sure the database and table are created before + ResultSet resultSet = stmt.executeQuery(sql)) { + + Timestamp ts; + float current; + String location; + while (resultSet.next()) { + ts = resultSet.getTimestamp(1); + current = resultSet.getFloat(2); + // we recommend using the column name to get the value + location = resultSet.getString("location"); + + // you can check data here + System.out.printf("ts: %s, current: %f, location: %s %n", ts, current, location); + } + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to query data from power.meters, sql: %s, %sErrMessage: %s%n", + sql, + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; + } +// ANCHOR_END: query_data + } +} diff --git a/docs/examples/java/src/main/java/com/taos/example/JdbcReqIdDemo.java b/docs/examples/java/src/main/java/com/taos/example/JdbcReqIdDemo.java new file mode 100644 index 0000000000..ee0ff45962 --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/JdbcReqIdDemo.java @@ -0,0 +1,64 @@ +package com.taos.example; + +import com.taosdata.jdbc.AbstractStatement; + +import java.sql.*; +import java.util.Properties; + +public class JdbcReqIdDemo { + private static final String host = "localhost"; + private static final String dbName = "test"; + private static final String tbName = "weather"; + private static final String user = "root"; + private static final String password = "taosdata"; + + + public static void main(String[] args) throws SQLException { + + final String jdbcUrl = "jdbc:TAOS://" + host + ":6030/?user=" + user + "&password=" + password; + +// get connection + Properties properties = new Properties(); + properties.setProperty("charset", "UTF-8"); + properties.setProperty("locale", "en_US.UTF-8"); + properties.setProperty("timezone", "UTC-8"); + System.out.println("get connection starting..."); + +// ANCHOR: with_reqid + long reqId = 3L; + try (Connection connection = DriverManager.getConnection(jdbcUrl, properties); + // Create a statement that allows specifying a request ID + AbstractStatement aStmt = (AbstractStatement) connection.createStatement()) { + + try (ResultSet resultSet = aStmt.executeQuery("SELECT ts, current, location FROM power.meters limit 1", reqId)) { + Timestamp ts; + float current; + String location; + while (resultSet.next()) { + ts = resultSet.getTimestamp(1); + current = resultSet.getFloat(2); + // we recommend using the column name to get the value + location = resultSet.getString("location"); + + // you can check data here + System.out.printf("ts: %s, current: %f, location: %s %n", ts, current, location); + + } + } + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to execute sql with reqId: %s, %sErrMessage: %s%n", reqId, + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; + } +// ANCHOR_END: with_reqid + } + + private static void printResult(ResultSet resultSet) throws SQLException { + Util.printResult(resultSet); + } + +} diff --git a/docs/examples/java/src/main/java/com/taos/example/ParameterBindingBasicDemo.java b/docs/examples/java/src/main/java/com/taos/example/ParameterBindingBasicDemo.java new file mode 100644 index 0000000000..8a8019e54e --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/ParameterBindingBasicDemo.java @@ -0,0 +1,90 @@ +package com.taos.example; + +import com.taosdata.jdbc.TSDBPreparedStatement; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Random; + +// ANCHOR: para_bind +public class ParameterBindingBasicDemo { + + // modify host to your own + private static final String host = "127.0.0.1"; + private static final Random random = new Random(System.currentTimeMillis()); + private static final int numOfSubTable = 10, numOfRow = 10; + + public static void main(String[] args) throws SQLException { + + String jdbcUrl = "jdbc:TAOS://" + host + ":6030/"; + try (Connection conn = DriverManager.getConnection(jdbcUrl, "root", "taosdata")) { + + init(conn); + + String sql = "INSERT INTO ? USING power.meters TAGS(?,?) VALUES (?,?,?,?)"; + + try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) { + + for (int i = 1; i <= numOfSubTable; i++) { + // set table name + pstmt.setTableName("d_bind_" + i); + + // set tags + pstmt.setTagInt(0, i); + pstmt.setTagString(1, "location_" + i); + + // set column ts + ArrayList tsList = new ArrayList<>(); + long current = System.currentTimeMillis(); + for (int j = 0; j < numOfRow; j++) + tsList.add(current + j); + pstmt.setTimestamp(0, tsList); + + // set column current + ArrayList currentList = new ArrayList<>(); + for (int j = 0; j < numOfRow; j++) + currentList.add(random.nextFloat() * 30); + pstmt.setFloat(1, currentList); + + // set column voltage + ArrayList voltageList = new ArrayList<>(); + for (int j = 0; j < numOfRow; j++) + voltageList.add(random.nextInt(300)); + pstmt.setInt(2, voltageList); + + // set column phase + ArrayList phaseList = new ArrayList<>(); + for (int j = 0; j < numOfRow; j++) + phaseList.add(random.nextFloat()); + pstmt.setFloat(3, phaseList); + // add column + pstmt.columnDataAddBatch(); + } + // execute column + pstmt.columnDataExecuteBatch(); + // you can check exeResult here + System.out.println("Successfully inserted " + (numOfSubTable * numOfRow) + " rows to power.meters."); + } + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to insert to table meters using stmt, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; + } + } + + private static void init(Connection conn) throws SQLException { + try (Statement stmt = conn.createStatement()) { + stmt.execute("CREATE DATABASE IF NOT EXISTS power"); + stmt.execute("USE power"); + stmt.execute("CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))"); + } + } +} +// ANCHOR_END: para_bind diff --git a/docs/examples/java/src/main/java/com/taos/example/ParameterBindingFullDemo.java b/docs/examples/java/src/main/java/com/taos/example/ParameterBindingFullDemo.java new file mode 100644 index 0000000000..5eb0cf0a61 --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/ParameterBindingFullDemo.java @@ -0,0 +1,325 @@ +package com.taos.example; + +import com.taosdata.jdbc.TSDBPreparedStatement; +import com.taosdata.jdbc.utils.StringUtils; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +// ANCHOR: para_bind +public class ParameterBindingFullDemo { + + private static final String host = "127.0.0.1"; + private static final Random random = new Random(System.currentTimeMillis()); + private static final int BINARY_COLUMN_SIZE = 50; + private static final String[] schemaList = { + "create table stable1(ts timestamp, f1 tinyint, f2 smallint, f3 int, f4 bigint) tags(t1 tinyint, t2 smallint, t3 int, t4 bigint)", + "create table stable2(ts timestamp, f1 float, f2 double) tags(t1 float, t2 double)", + "create table stable3(ts timestamp, f1 bool) tags(t1 bool)", + "create table stable4(ts timestamp, f1 binary(" + BINARY_COLUMN_SIZE + ")) tags(t1 binary(" + BINARY_COLUMN_SIZE + "))", + "create table stable5(ts timestamp, f1 nchar(" + BINARY_COLUMN_SIZE + ")) tags(t1 nchar(" + BINARY_COLUMN_SIZE + "))", + "create table stable6(ts timestamp, f1 varbinary(" + BINARY_COLUMN_SIZE + ")) tags(t1 varbinary(" + BINARY_COLUMN_SIZE + "))", + "create table stable7(ts timestamp, f1 geometry(" + BINARY_COLUMN_SIZE + ")) tags(t1 geometry(" + BINARY_COLUMN_SIZE + "))", + }; + private static final int numOfSubTable = 10, numOfRow = 10; + + public static void main(String[] args) throws SQLException { + + String jdbcUrl = "jdbc:TAOS://" + host + ":6030/"; + try (Connection conn = DriverManager.getConnection(jdbcUrl, "root", "taosdata")) { + + init(conn); + + bindInteger(conn); + bindFloat(conn); + bindBoolean(conn); + bindBytes(conn); + bindString(conn); + bindVarbinary(conn); + bindGeometry(conn); + + clean(conn); + } catch (SQLException ex) { + // handle any errors, please refer to the JDBC specifications for detailed exceptions info + System.out.println("Failed to insert to table meters using stmt, url: " + jdbcUrl + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); + throw ex; + } catch (Exception ex){ + System.out.println("Failed to insert to table meters using stmt, url: " + jdbcUrl + "; ErrMessage: " + ex.getMessage()); + throw ex; + } + } + + private static void init(Connection conn) throws SQLException { + clean(conn); + try (Statement stmt = conn.createStatement()) { + stmt.execute("create database if not exists test_parabind"); + stmt.execute("use test_parabind"); + for (int i = 0; i < schemaList.length; i++) { + stmt.execute(schemaList[i]); + } + } + } + private static void clean(Connection conn) throws SQLException { + try (Statement stmt = conn.createStatement()) { + stmt.execute("drop database if exists test_parabind"); + } + } + + private static void bindInteger(Connection conn) throws SQLException { + String sql = "insert into ? using stable1 tags(?,?,?,?) values(?,?,?,?,?)"; + + try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) { + + for (int i = 1; i <= numOfSubTable; i++) { + // set table name + pstmt.setTableName("t1_" + i); + // set tags + pstmt.setTagByte(0, Byte.parseByte(Integer.toString(random.nextInt(Byte.MAX_VALUE)))); + pstmt.setTagShort(1, Short.parseShort(Integer.toString(random.nextInt(Short.MAX_VALUE)))); + pstmt.setTagInt(2, random.nextInt(Integer.MAX_VALUE)); + pstmt.setTagLong(3, random.nextLong()); + // set columns + ArrayList tsList = new ArrayList<>(); + long current = System.currentTimeMillis(); + for (int j = 0; j < numOfRow; j++) + tsList.add(current + j); + pstmt.setTimestamp(0, tsList); + + ArrayList f1List = new ArrayList<>(); + for (int j = 0; j < numOfRow; j++) + f1List.add(Byte.parseByte(Integer.toString(random.nextInt(Byte.MAX_VALUE)))); + pstmt.setByte(1, f1List); + + ArrayList f2List = new ArrayList<>(); + for (int j = 0; j < numOfRow; j++) + f2List.add(Short.parseShort(Integer.toString(random.nextInt(Short.MAX_VALUE)))); + pstmt.setShort(2, f2List); + + ArrayList f3List = new ArrayList<>(); + for (int j = 0; j < numOfRow; j++) + f3List.add(random.nextInt(Integer.MAX_VALUE)); + pstmt.setInt(3, f3List); + + ArrayList f4List = new ArrayList<>(); + for (int j = 0; j < numOfRow; j++) + f4List.add(random.nextLong()); + pstmt.setLong(4, f4List); + + // add column + pstmt.columnDataAddBatch(); + } + // execute column + pstmt.columnDataExecuteBatch(); + } + } + + private static void bindFloat(Connection conn) throws SQLException { + String sql = "insert into ? using stable2 tags(?,?) values(?,?,?)"; + + TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class); + + for (int i = 1; i <= numOfSubTable; i++) { + // set table name + pstmt.setTableName("t2_" + i); + // set tags + pstmt.setTagFloat(0, random.nextFloat()); + pstmt.setTagDouble(1, random.nextDouble()); + // set columns + ArrayList tsList = new ArrayList<>(); + long current = System.currentTimeMillis(); + for (int j = 0; j < numOfRow; j++) + tsList.add(current + j); + pstmt.setTimestamp(0, tsList); + + ArrayList f1List = new ArrayList<>(); + for (int j = 0; j < numOfRow; j++) + f1List.add(random.nextFloat()); + pstmt.setFloat(1, f1List); + + ArrayList f2List = new ArrayList<>(); + for (int j = 0; j < numOfRow; j++) + f2List.add(random.nextDouble()); + pstmt.setDouble(2, f2List); + + // add column + pstmt.columnDataAddBatch(); + } + // execute + pstmt.columnDataExecuteBatch(); + // close if no try-with-catch statement is used + pstmt.close(); + } + + private static void bindBoolean(Connection conn) throws SQLException { + String sql = "insert into ? using stable3 tags(?) values(?,?)"; + + try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) { + for (int i = 1; i <= numOfSubTable; i++) { + // set table name + pstmt.setTableName("t3_" + i); + // set tags + pstmt.setTagBoolean(0, random.nextBoolean()); + // set columns + ArrayList tsList = new ArrayList<>(); + long current = System.currentTimeMillis(); + for (int j = 0; j < numOfRow; j++) + tsList.add(current + j); + pstmt.setTimestamp(0, tsList); + + ArrayList f1List = new ArrayList<>(); + for (int j = 0; j < numOfRow; j++) + f1List.add(random.nextBoolean()); + pstmt.setBoolean(1, f1List); + + // add column + pstmt.columnDataAddBatch(); + } + // execute + pstmt.columnDataExecuteBatch(); + } + } + + private static void bindBytes(Connection conn) throws SQLException { + String sql = "insert into ? using stable4 tags(?) values(?,?)"; + + try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) { + + for (int i = 1; i <= numOfSubTable; i++) { + // set table name + pstmt.setTableName("t4_" + i); + // set tags + pstmt.setTagString(0, new String("abc")); + + // set columns + ArrayList tsList = new ArrayList<>(); + long current = System.currentTimeMillis(); + for (int j = 0; j < numOfRow; j++) + tsList.add(current + j); + pstmt.setTimestamp(0, tsList); + + ArrayList f1List = new ArrayList<>(); + for (int j = 0; j < numOfRow; j++) { + f1List.add(new String("abc")); + } + pstmt.setString(1, f1List, BINARY_COLUMN_SIZE); + + // add column + pstmt.columnDataAddBatch(); + } + // execute + pstmt.columnDataExecuteBatch(); + } + } + + private static void bindString(Connection conn) throws SQLException { + String sql = "insert into ? using stable5 tags(?) values(?,?)"; + + try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) { + + for (int i = 1; i <= numOfSubTable; i++) { + // set table name + pstmt.setTableName("t5_" + i); + // set tags + pstmt.setTagNString(0, "California.SanFrancisco"); + + // set columns + ArrayList tsList = new ArrayList<>(); + long current = System.currentTimeMillis(); + for (int j = 0; j < numOfRow; j++) + tsList.add(current + j); + pstmt.setTimestamp(0, tsList); + + ArrayList f1List = new ArrayList<>(); + for (int j = 0; j < numOfRow; j++) { + f1List.add("California.LosAngeles"); + } + pstmt.setNString(1, f1List, BINARY_COLUMN_SIZE); + + // add column + pstmt.columnDataAddBatch(); + } + // execute + pstmt.columnDataExecuteBatch(); + } + } + + private static void bindVarbinary(Connection conn) throws SQLException { + String sql = "insert into ? using stable6 tags(?) values(?,?)"; + + try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) { + + for (int i = 1; i <= numOfSubTable; i++) { + // set table name + pstmt.setTableName("t6_" + i); + // set tags + byte[] bTag = new byte[]{0,2,3,4,5}; + bTag[0] = (byte) i; + pstmt.setTagVarbinary(0, bTag); + + // set columns + ArrayList tsList = new ArrayList<>(); + long current = System.currentTimeMillis(); + for (int j = 0; j < numOfRow; j++) + tsList.add(current + j); + pstmt.setTimestamp(0, tsList); + + ArrayList f1List = new ArrayList<>(); + for (int j = 0; j < numOfRow; j++) { + byte[] v = new byte[]{0,2,3,4,5,6}; + v[0] = (byte)j; + f1List.add(v); + } + pstmt.setVarbinary(1, f1List, BINARY_COLUMN_SIZE); + + // add column + pstmt.columnDataAddBatch(); + } + // execute + pstmt.columnDataExecuteBatch(); + } + } + + private static void bindGeometry(Connection conn) throws SQLException { + String sql = "insert into ? using stable7 tags(?) values(?,?)"; + + try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) { + + byte[] g1 = StringUtils.hexToBytes("0101000000000000000000F03F0000000000000040"); + byte[] g2 = StringUtils.hexToBytes("0102000020E610000002000000000000000000F03F000000000000004000000000000008400000000000001040"); + List listGeo = new ArrayList<>(); + listGeo.add(g1); + listGeo.add(g2); + + for (int i = 1; i <= 2; i++) { + // set table name + pstmt.setTableName("t7_" + i); + // set tags + pstmt.setTagGeometry(0, listGeo.get(i - 1)); + + // set columns + ArrayList tsList = new ArrayList<>(); + long current = System.currentTimeMillis(); + for (int j = 0; j < numOfRow; j++) + tsList.add(current + j); + pstmt.setTimestamp(0, tsList); + + ArrayList f1List = new ArrayList<>(); + for (int j = 0; j < numOfRow; j++) { + f1List.add(listGeo.get(i - 1)); + } + pstmt.setGeometry(1, f1List, BINARY_COLUMN_SIZE); + + // add column + pstmt.columnDataAddBatch(); + } + // execute + pstmt.columnDataExecuteBatch(); + } + } +} +// ANCHOR_END: para_bind diff --git a/docs/examples/java/src/main/java/com/taos/example/RESTConnectExample.java b/docs/examples/java/src/main/java/com/taos/example/RESTConnectExample.java index b1ec31ee86..441d478b07 100644 --- a/docs/examples/java/src/main/java/com/taos/example/RESTConnectExample.java +++ b/docs/examples/java/src/main/java/com/taos/example/RESTConnectExample.java @@ -5,22 +5,24 @@ import java.sql.DriverManager; import java.sql.SQLException; public class RESTConnectExample { -// ANCHOR: main -public static void main(String[] args) throws SQLException { - String jdbcUrl = "jdbc:TAOS-RS://localhost:6041?user=root&password=taosdata"; - try (Connection conn = DriverManager.getConnection(jdbcUrl)){ - System.out.println("Connected to " + jdbcUrl + " successfully."); + // ANCHOR: main + public static void main(String[] args) throws Exception { + String jdbcUrl = "jdbc:TAOS-RS://localhost:6041?user=root&password=taosdata"; + try (Connection conn = DriverManager.getConnection(jdbcUrl)) { + System.out.println("Connected to " + jdbcUrl + " successfully."); - // you can use the connection for execute SQL here + // you can use the connection for execute SQL here - } catch (SQLException ex) { - // handle any errors, please refer to the JDBC specifications for detailed exceptions info - System.out.println("Failed to connect to " + jdbcUrl + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw ex; - } catch (Exception ex){ - System.out.println("Failed to connect to " + jdbcUrl + "; ErrMessage: " + ex.getMessage()); - throw ex; + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to connect to %s, %sErrMessage: %s%n", + jdbcUrl, + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; + } } + // ANCHOR_END: main } -// ANCHOR_END: main -} \ No newline at end of file diff --git a/docs/examples/java/src/main/java/com/taos/example/SchemalessJniTest.java b/docs/examples/java/src/main/java/com/taos/example/SchemalessJniTest.java new file mode 100644 index 0000000000..818dda90d8 --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/SchemalessJniTest.java @@ -0,0 +1,47 @@ +package com.taos.example; + +import com.taosdata.jdbc.AbstractConnection; +import com.taosdata.jdbc.enums.SchemalessProtocolType; +import com.taosdata.jdbc.enums.SchemalessTimestampType; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; + +// ANCHOR: schemaless +public class SchemalessJniTest { + private static final String host = "127.0.0.1"; + private static final String lineDemo = "meters,groupid=2,location=California.SanFrancisco current=10.3000002f64,voltage=219i32,phase=0.31f64 1626006833639"; + private static final String telnetDemo = "metric_telnet 1707095283260 4 host=host0 interface=eth0"; + private static final String jsonDemo = "{\"metric\": \"metric_json\",\"timestamp\": 1626846400,\"value\": 10.3, \"tags\": {\"groupid\": 2, \"location\": \"California.SanFrancisco\", \"id\": \"d1001\"}}"; + + public static void main(String[] args) throws SQLException { + final String jdbcUrl = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; + try (Connection connection = DriverManager.getConnection(jdbcUrl)) { + init(connection); + AbstractConnection conn = connection.unwrap(AbstractConnection.class); + + conn.write(lineDemo, SchemalessProtocolType.LINE, SchemalessTimestampType.MILLI_SECONDS); + conn.write(telnetDemo, SchemalessProtocolType.TELNET, SchemalessTimestampType.MILLI_SECONDS); + conn.write(jsonDemo, SchemalessProtocolType.JSON, SchemalessTimestampType.NOT_CONFIGURED); + System.out.println("Inserted data with schemaless successfully."); + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to insert data with schemaless, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; + } + } + + private static void init(Connection connection) throws SQLException { + try (Statement stmt = connection.createStatement()) { + stmt.execute("CREATE DATABASE IF NOT EXISTS power"); + stmt.execute("USE power"); + } + } +} +// ANCHOR_END: schemaless diff --git a/docs/examples/java/src/main/java/com/taos/example/SchemalessWsTest.java b/docs/examples/java/src/main/java/com/taos/example/SchemalessWsTest.java new file mode 100644 index 0000000000..08f66c2227 --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/SchemalessWsTest.java @@ -0,0 +1,47 @@ +package com.taos.example; + +import com.taosdata.jdbc.AbstractConnection; +import com.taosdata.jdbc.enums.SchemalessProtocolType; +import com.taosdata.jdbc.enums.SchemalessTimestampType; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; + +// ANCHOR: schemaless +public class SchemalessWsTest { + private static final String host = "127.0.0.1"; + private static final String lineDemo = "meters,groupid=2,location=California.SanFrancisco current=10.3000002f64,voltage=219i32,phase=0.31f64 1626006833639"; + private static final String telnetDemo = "metric_telnet 1707095283260 4 host=host0 interface=eth0"; + private static final String jsonDemo = "{\"metric\": \"metric_json\",\"timestamp\": 1626846400,\"value\": 10.3, \"tags\": {\"groupid\": 2, \"location\": \"California.SanFrancisco\", \"id\": \"d1001\"}}"; + + public static void main(String[] args) throws SQLException { + final String url = "jdbc:TAOS-RS://" + host + ":6041?user=root&password=taosdata&batchfetch=true"; + try(Connection connection = DriverManager.getConnection(url)){ + init(connection); + AbstractConnection conn = connection.unwrap(AbstractConnection.class); + + conn.write(lineDemo, SchemalessProtocolType.LINE, SchemalessTimestampType.MILLI_SECONDS); + conn.write(telnetDemo, SchemalessProtocolType.TELNET, SchemalessTimestampType.MILLI_SECONDS); + conn.write(jsonDemo, SchemalessProtocolType.JSON, SchemalessTimestampType.SECONDS); + System.out.println("Inserted data with schemaless successfully."); + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to insert data with schemaless, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; + } + } + + private static void init(Connection connection) throws SQLException { + try (Statement stmt = connection.createStatement()) { + stmt.execute("CREATE DATABASE IF NOT EXISTS power"); + stmt.execute("USE power"); + } + } +} +// ANCHOR_END: schemaless diff --git a/docs/examples/java/src/main/java/com/taos/example/Util.java b/docs/examples/java/src/main/java/com/taos/example/Util.java new file mode 100644 index 0000000000..79a1d8628b --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/Util.java @@ -0,0 +1,25 @@ +package com.taos.example; + +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; + +public class Util { + public static void printResult(ResultSet resultSet) throws SQLException { + ResultSetMetaData metaData = resultSet.getMetaData(); + for (int i = 1; i <= metaData.getColumnCount(); i++) { + String columnLabel = metaData.getColumnLabel(i); + System.out.printf(" %s |", columnLabel); + } + System.out.println(); + System.out.println("-------------------------------------------------------------"); + while (resultSet.next()) { + for (int i = 1; i <= metaData.getColumnCount(); i++) { + String value = resultSet.getString(i); + System.out.printf("%s, ", value); + } + System.out.println(); + } + } + +} diff --git a/docs/examples/java/src/main/java/com/taos/example/WSConnectExample.java b/docs/examples/java/src/main/java/com/taos/example/WSConnectExample.java index 21f184b45a..afe74ace83 100644 --- a/docs/examples/java/src/main/java/com/taos/example/WSConnectExample.java +++ b/docs/examples/java/src/main/java/com/taos/example/WSConnectExample.java @@ -9,7 +9,7 @@ import java.util.Properties; public class WSConnectExample { // ANCHOR: main - public static void main(String[] args) throws SQLException { + public static void main(String[] args) throws Exception { // use // String jdbcUrl = // "jdbc:TAOS-RS://localhost:6041/dbName?user=root&password=taosdata&batchfetch=true"; @@ -25,14 +25,14 @@ public class WSConnectExample { // you can use the connection for execute SQL here - } catch (SQLException ex) { - // handle any errors, please refer to the JDBC specifications for detailed - // exceptions info - System.out.println("Failed to connect to " + jdbcUrl + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " - + ex.getMessage()); - throw ex; } catch (Exception ex) { - System.out.println("Failed to connect to " + jdbcUrl + "; ErrMessage: " + ex.getMessage()); + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to connect to %s, %sErrMessage: %s%n", + jdbcUrl, + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); throw ex; } } diff --git a/docs/examples/java/src/main/java/com/taos/example/WSParameterBindingBasicDemo.java b/docs/examples/java/src/main/java/com/taos/example/WSParameterBindingBasicDemo.java new file mode 100644 index 0000000000..eab8df06b9 --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/WSParameterBindingBasicDemo.java @@ -0,0 +1,67 @@ +package com.taos.example; + +import com.taosdata.jdbc.ws.TSWSPreparedStatement; + +import java.sql.*; +import java.util.Random; + +// ANCHOR: para_bind +public class WSParameterBindingBasicDemo { + + // modify host to your own + private static final String host = "127.0.0.1"; + private static final Random random = new Random(System.currentTimeMillis()); + private static final int numOfSubTable = 10, numOfRow = 10; + + public static void main(String[] args) throws SQLException { + + String jdbcUrl = "jdbc:TAOS-RS://" + host + ":6041/?batchfetch=true"; + try (Connection conn = DriverManager.getConnection(jdbcUrl, "root", "taosdata")) { + init(conn); + + String sql = "INSERT INTO ? USING power.meters TAGS(?,?) VALUES (?,?,?,?)"; + + try (TSWSPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSWSPreparedStatement.class)) { + + for (int i = 1; i <= numOfSubTable; i++) { + // set table name + pstmt.setTableName("d_bind_" + i); + + // set tags + pstmt.setTagInt(0, i); + pstmt.setTagString(1, "location_" + i); + + // set columns + long current = System.currentTimeMillis(); + for (int j = 0; j < numOfRow; j++) { + pstmt.setTimestamp(1, new Timestamp(current + j)); + pstmt.setFloat(2, random.nextFloat() * 30); + pstmt.setInt(3, random.nextInt(300)); + pstmt.setFloat(4, random.nextFloat()); + pstmt.addBatch(); + } + int [] exeResult = pstmt.executeBatch(); + // you can check exeResult here + System.out.println("Successfully inserted " + exeResult.length + " rows to power.meters."); + } + } + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to insert to table meters using stmt, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; + } + } + + private static void init(Connection conn) throws SQLException { + try (Statement stmt = conn.createStatement()) { + stmt.execute("CREATE DATABASE IF NOT EXISTS power"); + stmt.execute("USE power"); + stmt.execute("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))"); + } + } +} +// ANCHOR_END: para_bind diff --git a/docs/examples/java/src/main/java/com/taos/example/WSParameterBindingFullDemo.java b/docs/examples/java/src/main/java/com/taos/example/WSParameterBindingFullDemo.java new file mode 100644 index 0000000000..ec94f2ded6 --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/WSParameterBindingFullDemo.java @@ -0,0 +1,180 @@ +package com.taos.example; + +import com.taosdata.jdbc.ws.TSWSPreparedStatement; + +import java.sql.*; +import java.util.Random; + +// ANCHOR: para_bind +public class WSParameterBindingFullDemo { + private static final String host = "127.0.0.1"; + private static final Random random = new Random(System.currentTimeMillis()); + private static final int BINARY_COLUMN_SIZE = 30; + private static final String[] schemaList = { + "create table stable1(ts timestamp, f1 tinyint, f2 smallint, f3 int, f4 bigint) tags(t1 tinyint, t2 smallint, t3 int, t4 bigint)", + "create table stable2(ts timestamp, f1 float, f2 double) tags(t1 float, t2 double)", + "create table stable3(ts timestamp, f1 bool) tags(t1 bool)", + "create table stable4(ts timestamp, f1 binary(" + BINARY_COLUMN_SIZE + ")) tags(t1 binary(" + BINARY_COLUMN_SIZE + "))", + "create table stable5(ts timestamp, f1 nchar(" + BINARY_COLUMN_SIZE + ")) tags(t1 nchar(" + BINARY_COLUMN_SIZE + "))" + }; + private static final int numOfSubTable = 10, numOfRow = 10; + + public static void main(String[] args) throws SQLException { + + String jdbcUrl = "jdbc:TAOS-RS://" + host + ":6041/?batchfetch=true"; + + try (Connection conn = DriverManager.getConnection(jdbcUrl, "root", "taosdata")) { + + init(conn); + + bindInteger(conn); + + bindFloat(conn); + + bindBoolean(conn); + + bindBytes(conn); + + bindString(conn); + + } catch (SQLException ex) { + // handle any errors, please refer to the JDBC specifications for detailed exceptions info + System.out.println("Failed to insert to table meters using stmt, url: " + jdbcUrl + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); + throw ex; + } catch (Exception ex){ + System.out.println("Failed to insert to table meters using stmt, url: " + jdbcUrl + "; ErrMessage: " + ex.getMessage()); + throw ex; + } + } + + private static void init(Connection conn) throws SQLException { + try (Statement stmt = conn.createStatement()) { + stmt.execute("drop database if exists test_ws_parabind"); + stmt.execute("create database if not exists test_ws_parabind"); + stmt.execute("use test_ws_parabind"); + for (int i = 0; i < schemaList.length; i++) { + stmt.execute(schemaList[i]); + } + } + } + + private static void bindInteger(Connection conn) throws SQLException { + String sql = "insert into ? using stable1 tags(?,?,?,?) values(?,?,?,?,?)"; + + try (TSWSPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSWSPreparedStatement.class)) { + + for (int i = 1; i <= numOfSubTable; i++) { + // set table name + pstmt.setTableName("t1_" + i); + // set tags + pstmt.setTagByte(1, Byte.parseByte(Integer.toString(random.nextInt(Byte.MAX_VALUE)))); + pstmt.setTagShort(2, Short.parseShort(Integer.toString(random.nextInt(Short.MAX_VALUE)))); + pstmt.setTagInt(3, random.nextInt(Integer.MAX_VALUE)); + pstmt.setTagLong(4, random.nextLong()); + // set columns + long current = System.currentTimeMillis(); + for (int j = 0; j < numOfRow; j++) { + pstmt.setTimestamp(1, new Timestamp(current + j)); + pstmt.setByte(2, Byte.parseByte(Integer.toString(random.nextInt(Byte.MAX_VALUE)))); + pstmt.setShort(3, Short.parseShort(Integer.toString(random.nextInt(Short.MAX_VALUE)))); + pstmt.setInt(4, random.nextInt(Integer.MAX_VALUE)); + pstmt.setLong(5, random.nextLong()); + pstmt.addBatch(); + } + pstmt.executeBatch(); + } + } + } + + private static void bindFloat(Connection conn) throws SQLException { + String sql = "insert into ? using stable2 tags(?,?) values(?,?,?)"; + + try(TSWSPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSWSPreparedStatement.class)) { + + for (int i = 1; i <= numOfSubTable; i++) { + // set table name + pstmt.setTableName("t2_" + i); + // set tags + pstmt.setTagFloat(1, random.nextFloat()); + pstmt.setTagDouble(2, random.nextDouble()); + // set columns + long current = System.currentTimeMillis(); + for (int j = 0; j < numOfRow; j++) { + pstmt.setTimestamp(1, new Timestamp(current + j)); + pstmt.setFloat(2, random.nextFloat()); + pstmt.setDouble(3, random.nextDouble()); + pstmt.addBatch(); + } + pstmt.executeBatch(); + } + } + } + + private static void bindBoolean(Connection conn) throws SQLException { + String sql = "insert into ? using stable3 tags(?) values(?,?)"; + + try (TSWSPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSWSPreparedStatement.class)) { + for (int i = 1; i <= numOfSubTable; i++) { + // set table name + pstmt.setTableName("t3_" + i); + // set tags + pstmt.setTagBoolean(1, random.nextBoolean()); + // set columns + long current = System.currentTimeMillis(); + for (int j = 0; j < numOfRow; j++) { + pstmt.setTimestamp(1, new Timestamp(current + j)); + pstmt.setBoolean(2, random.nextBoolean()); + pstmt.addBatch(); + } + pstmt.executeBatch(); + } + } + } + + private static void bindBytes(Connection conn) throws SQLException { + String sql = "insert into ? using stable4 tags(?) values(?,?)"; + + try (TSWSPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSWSPreparedStatement.class)) { + + for (int i = 1; i <= numOfSubTable; i++) { + // set table name + pstmt.setTableName("t4_" + i); + // set tags + pstmt.setTagString(1, new String("abc")); + + // set columns + long current = System.currentTimeMillis(); + for (int j = 0; j < numOfRow; j++) { + pstmt.setTimestamp(1, new Timestamp(current + j)); + pstmt.setString(2, "abc"); + pstmt.addBatch(); + } + pstmt.executeBatch(); + } + } + } + + private static void bindString(Connection conn) throws SQLException { + String sql = "insert into ? using stable5 tags(?) values(?,?)"; + + try (TSWSPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSWSPreparedStatement.class)) { + + for (int i = 1; i <= numOfSubTable; i++) { + // set table name + pstmt.setTableName("t5_" + i); + // set tags + pstmt.setTagNString(1, "California.SanFrancisco"); + + // set columns + long current = System.currentTimeMillis(); + for (int j = 0; j < numOfRow; j++) { + pstmt.setTimestamp(0, new Timestamp(current + j)); + pstmt.setNString(1, "California.SanFrancisco"); + pstmt.addBatch(); + } + pstmt.executeBatch(); + } + } + } +} +// ANCHOR_END: para_bind diff --git a/docs/examples/java/src/main/java/com/taos/example/WsConsumerLoopFull.java b/docs/examples/java/src/main/java/com/taos/example/WsConsumerLoopFull.java new file mode 100644 index 0000000000..66c37f172e --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/WsConsumerLoopFull.java @@ -0,0 +1,384 @@ +package com.taos.example; + +import com.alibaba.fastjson.JSON; +import com.taosdata.jdbc.TSDBDriver; +import com.taosdata.jdbc.tmq.*; + +import java.sql.*; +import java.time.Duration; +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +// ANCHOR: consumer_demo +public class WsConsumerLoopFull { + static private Connection connection; + static private Statement statement; + static private volatile boolean stopThread = false; + + public static TaosConsumer getConsumer() throws Exception { +// ANCHOR: create_consumer + Properties config = new Properties(); + config.setProperty("td.connect.type", "ws"); + config.setProperty("bootstrap.servers", "localhost:6041"); + config.setProperty("auto.offset.reset", "latest"); + config.setProperty("msg.with.table.name", "true"); + config.setProperty("enable.auto.commit", "true"); + config.setProperty("auto.commit.interval.ms", "1000"); + config.setProperty("group.id", "group1"); + config.setProperty("client.id", "1"); + config.setProperty("td.connect.user", "root"); + config.setProperty("td.connect.pass", "taosdata"); + config.setProperty("value.deserializer", "com.taos.example.WsConsumerLoopFull$ResultDeserializer"); + config.setProperty("value.deserializer.encoding", "UTF-8"); + + try { + TaosConsumer consumer= new TaosConsumer<>(config); + System.out.printf("Create consumer successfully, host: %s, groupId: %s, clientId: %s%n", + config.getProperty("bootstrap.servers"), + config.getProperty("group.id"), + config.getProperty("client.id")); + return consumer; + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to create websocket consumer, host: %s, %sErrMessage: %s%n", + config.getProperty("bootstrap.servers"), + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; + } +// ANCHOR_END: create_consumer + } + + public static void pollExample(TaosConsumer consumer) throws SQLException { +// ANCHOR: poll_data_code_piece + try { + List topics = Collections.singletonList("topic_meters"); + + // subscribe to the topics + consumer.subscribe(topics); + System.out.println("Subscribe topics successfully."); + for (int i = 0; i < 50; i++) { + // poll data + ConsumerRecords records = consumer.poll(Duration.ofMillis(100)); + for (ConsumerRecord record : records) { + ResultBean bean = record.value(); + // process the data here + System.out.println("data: " + JSON.toJSONString(bean)); + } + } + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to poll data, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; + } +// ANCHOR_END: poll_data_code_piece + } + + public static void seekExample(TaosConsumer consumer) throws SQLException { +// ANCHOR: consumer_seek + try { + List topics = Collections.singletonList("topic_meters"); + + // subscribe to the topics + consumer.subscribe(topics); + System.out.println("Subscribe topics successfully."); + Set assignment = consumer.assignment(); + System.out.println("Now assignment: " + JSON.toJSONString(assignment)); + + ConsumerRecords records = ConsumerRecords.emptyRecord(); + // make sure we have got some data + while (records.isEmpty()) { + records = consumer.poll(Duration.ofMillis(100)); + } + + consumer.seekToBeginning(assignment); + System.out.println("Assignment seek to beginning successfully."); + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to execute seek example, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; + } +// ANCHOR_END: consumer_seek + } + + + public static void commitExample(TaosConsumer consumer) throws SQLException { +// ANCHOR: commit_code_piece + try { + List topics = Collections.singletonList("topic_meters"); + + consumer.subscribe(topics); + for (int i = 0; i < 50; i++) { + ConsumerRecords records = consumer.poll(Duration.ofMillis(100)); + for (ConsumerRecord record : records) { + ResultBean bean = record.value(); + // process your data here + System.out.println("data: " + JSON.toJSONString(bean)); + } + if (!records.isEmpty()) { + // after processing the data, commit the offset manually + consumer.commitSync(); + System.out.println("Commit offset manually successfully."); + } + } + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to execute commit example, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; + } +// ANCHOR_END: commit_code_piece + } + + public static void unsubscribeExample(TaosConsumer consumer) throws SQLException { + List topics = Collections.singletonList("topic_meters"); + consumer.subscribe(topics); +// ANCHOR: unsubscribe_data_code_piece + try { + // unsubscribe the consumer + consumer.unsubscribe(); + System.out.println("Consumer unsubscribed successfully."); + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to unsubscribe consumer, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; + } + finally { + // close the consumer + consumer.close(); + System.out.println("Consumer closed successfully."); + } +// ANCHOR_END: unsubscribe_data_code_piece + } + + public static class ResultDeserializer extends ReferenceDeserializer { + + } + + // use this class to define the data structure of the result record + public static class ResultBean { + private Timestamp ts; + private double current; + private int voltage; + private double phase; + private int groupid; + private String location; + + public Timestamp getTs() { + return ts; + } + + public void setTs(Timestamp ts) { + this.ts = ts; + } + + public double getCurrent() { + return current; + } + + public void setCurrent(double current) { + this.current = current; + } + + public int getVoltage() { + return voltage; + } + + public void setVoltage(int voltage) { + this.voltage = voltage; + } + + public double getPhase() { + return phase; + } + + public void setPhase(double phase) { + this.phase = phase; + } + + public int getGroupid() { + return groupid; + } + + public void setGroupid(int groupid) { + this.groupid = groupid; + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + } + + public static void prepareData() throws SQLException, InterruptedException { + try { + int i = 0; + while (!stopThread) { + String insertQuery = "INSERT INTO power.d1001 USING power.meters TAGS(2,'California.SanFrancisco') VALUES (NOW + " + i + "a, 10.30000, 219, 0.31000) "; + int affectedRows = statement.executeUpdate(insertQuery); + assert affectedRows == 1; + i++; + Thread.sleep(1); + } + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to insert data to power.meters, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; + } + } + + public static void prepareMeta() throws SQLException { + try { + statement.executeUpdate("CREATE DATABASE IF NOT EXISTS power"); + statement.executeUpdate("USE power"); + statement.executeUpdate("CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))"); + statement.executeUpdate("CREATE TOPIC IF NOT EXISTS topic_meters AS SELECT ts, current, voltage, phase, groupid, location FROM meters"); + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to create db and table, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; + } + } + + public static void initConnection() throws SQLException { + String url = "jdbc:TAOS://localhost:6030?user=root&password=taosdata"; + Properties properties = new Properties(); + properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "C"); + properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); + + try { + connection = DriverManager.getConnection(url, properties); + } catch (SQLException ex) { + System.out.println("Failed to create connection, url:" + url + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); + throw new SQLException("Failed to create connection", ex); + } + try { + statement = connection.createStatement(); + } catch (SQLException ex) { + System.out.println("Failed to create statement, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); + throw new SQLException("Failed to create statement", ex); + } + System.out.println("Connection created successfully."); + } + + public static void closeConnection() throws SQLException { + try { + if (statement != null) { + statement.close(); + } + } catch (SQLException ex) { + System.out.println("Failed to close statement, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); + throw new SQLException("Failed to close statement", ex); + } + + try { + if (connection != null) { + connection.close(); + } + } catch (SQLException ex) { + System.out.println("Failed to close connection, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); + throw new SQLException("Failed to close connection", ex); + } + System.out.println("Connection closed Successfully."); + } + + + public static void main(String[] args) throws SQLException, InterruptedException { + initConnection(); + prepareMeta(); + + // create a single thread executor + ExecutorService executor = Executors.newSingleThreadExecutor(); + + // submit a task + executor.submit(() -> { + try { + prepareData(); + } catch (SQLException ex) { + System.out.println("Failed to prepare data, ErrCode:" + ex.getErrorCode() + ", ErrMessage: " + ex.getMessage()); + return; + } catch (Exception ex) { + System.out.println("Failed to prepare data, ErrMessage: " + ex.getMessage()); + return; + } + System.out.println("pollDataExample executed successfully."); + }); + + try { + TaosConsumer consumer = getConsumer(); + + pollExample(consumer); + System.out.println("pollExample executed successfully."); + consumer.unsubscribe(); + + seekExample(consumer); + System.out.println("seekExample executed successfully."); + consumer.unsubscribe(); + + commitExample(consumer); + System.out.println("commitExample executed successfully."); + consumer.unsubscribe(); + + unsubscribeExample(consumer); + System.out.println("unsubscribeExample executed successfully"); + } catch (SQLException ex) { + System.out.println("Failed to poll data from topic_meters, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); + return; + } catch (Exception ex) { + System.out.println("Failed to poll data from topic_meters, ErrMessage: " + ex.getMessage()); + return; + } + + stopThread = true; + // close the executor, which will make the executor reject new tasks + executor.shutdown(); + + try { + // wait for the executor to terminate + boolean result = executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); + assert result; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Wait executor termination failed."); + } + + closeConnection(); + System.out.println("program end."); + } +} +// ANCHOR_END: consumer_demo diff --git a/docs/examples/node/websocketexample/line_example.js b/docs/examples/node/websocketexample/line_example.js index 7e76db2677..4fc5042f5a 100644 --- a/docs/examples/node/websocketexample/line_example.js +++ b/docs/examples/node/websocketexample/line_example.js @@ -28,7 +28,7 @@ async function test() { console.log("Inserted data with schemaless successfully.") } catch (err) { - console.error("Failed to insert data with schemaless, url:"+ dsn +", ErrCode:" + err.code + "; ErrMessage: " + err.message); + console.error("Failed to insert data with schemaless, ErrCode: " + err.code + ", ErrMessage: " + err.message); } finally { if (wsRows) { @@ -40,4 +40,4 @@ async function test() { taos.destroy(); } } -test() \ No newline at end of file +test() diff --git a/docs/examples/node/websocketexample/sql_example.js b/docs/examples/node/websocketexample/sql_example.js index e36bd037ed..8ef4dcb831 100644 --- a/docs/examples/node/websocketexample/sql_example.js +++ b/docs/examples/node/websocketexample/sql_example.js @@ -9,11 +9,11 @@ async function createConnect() { conf.setUser('root'); conf.setPwd('taosdata'); conf.setDb('power'); - conn = await taos.sqlConnect(conf); + conn = await taos.sqlConnect(conf); console.log("Connected to " + dsn + " successfully."); - return conn; + return conn; } catch (err) { - console.log("Failed to connect to " + dns + "; ErrCode:" + err.code + "; ErrMessage: " + err.message); + console.log("Failed to connect to " + dns + ", ErrCode: " + err.code + ", ErrMessage: " + err.message); throw err; } @@ -29,13 +29,13 @@ async function createDbAndTable() { await wsSql.exec('CREATE DATABASE IF NOT EXISTS power'); console.log("Create database power successfully."); // create table - await wsSql.exec('CREATE STABLE IF NOT EXISTS power.meters ' + - '(_ts timestamp, current float, voltage int, phase float) ' + - 'TAGS (location binary(64), groupId int);'); + await wsSql.exec('CREATE STABLE IF NOT EXISTS power.meters ' + + '(_ts timestamp, current float, voltage int, phase float) ' + + 'TAGS (location binary(64), groupId int);'); console.log("Create stable power.meters successfully"); } catch (err) { - console.error("Failed to create db and table, url:" + dns + "; ErrCode:" + err.code + "; ErrMessage: " + err.message); + console.error("Failed to create database power or stable meters, ErrCode: " + err.code + ", ErrMessage: " + err.message); } finally { if (wsSql) { await wsSql.close(); @@ -51,18 +51,18 @@ async function insertData() { try { wsSql = await createConnect(); let insertQuery = "INSERT INTO " + - "power.d1001 USING power.meters (location, groupId) TAGS('California.SanFrancisco', 2) " + - "VALUES " + - "(NOW + 1a, 10.30000, 219, 0.31000) " + - "(NOW + 2a, 12.60000, 218, 0.33000) " + - "(NOW + 3a, 12.30000, 221, 0.31000) " + - "power.d1002 USING power.meters TAGS('California.SanFrancisco', 3) " + - "VALUES " + - "(NOW + 1a, 10.30000, 218, 0.25000) "; + "power.d1001 USING power.meters (location, groupId) TAGS('California.SanFrancisco', 2) " + + "VALUES " + + "(NOW + 1a, 10.30000, 219, 0.31000) " + + "(NOW + 2a, 12.60000, 218, 0.33000) " + + "(NOW + 3a, 12.30000, 221, 0.31000) " + + "power.d1002 USING power.meters TAGS('California.SanFrancisco', 3) " + + "VALUES " + + "(NOW + 1a, 10.30000, 218, 0.25000) "; taosResult = await wsSql.exec(insertQuery); console.log("Successfully inserted " + taosResult.getAffectRows() + " rows to power.meters."); } catch (err) { - console.error("Failed to insert data to power.meters, url:" + dsn + "; ErrCode:" + err.code + "; ErrMessage: " + err.message); + console.error("Failed to insert data to power.meters, ErrCode: " + err.code + ", ErrMessage: " + err.message); } finally { if (wsSql) { await wsSql.close(); @@ -75,21 +75,22 @@ async function insertData() { async function queryData() { let wsRows = null; let wsSql = null; + let sql = 'SELECT ts, current, location FROM power.meters limit 100'; try { wsSql = await createConnect(); - wsRows = await wsSql.query('SELECT ts, current, location FROM power.meters limit 100'); + wsRows = await wsSql.query(sql); while (await wsRows.next()) { let row = wsRows.getData(); - console.log('ts: ' + row[0] + ', current: ' + row[1] + ', location: ' + row[2]); + console.log('ts: ' + row[0] + ', current: ' + row[1] + ', location: ' + row[2]); } } catch (err) { - console.error("Failed to query data from power.meters, url:" + dsn + " ; ErrCode:" + err.code + "; ErrMessage: " + err.message); + console.error("Failed to query data from power.meters, sql: " + sql + ", ErrCode:" + err.code + ", ErrMessage: " + err.message); } finally { if (wsRows) { await wsRows.close(); - } + } if (wsSql) { await wsSql.close(); } @@ -107,16 +108,16 @@ async function sqlWithReqid() { wsRows = await wsSql.query('SELECT ts, current, location FROM power.meters limit 100', reqId); while (await wsRows.next()) { let row = wsRows.getData(); - console.log('ts: ' + row[0] + ', current: ' + row[1] + ', location: ' + row[2]); + console.log('ts: ' + row[0] + ', current: ' + row[1] + ', location: ' + row[2]); } } catch (err) { - console.error("Failed to execute sql with reqId: " + reqId + ", ErrCode:" + err.code + "; ErrMessage: " + err.message); + console.error("Failed to execute sql with reqId: " + reqId + ", ErrCode: " + err.code + ", ErrMessage: " + err.message); } finally { if (wsRows) { await wsRows.close(); - } + } if (wsSql) { await wsSql.close(); } @@ -129,7 +130,7 @@ async function test() { await insertData(); await queryData(); await sqlWithReqid(); - taos.destroy(); + taos.destroy(); } -test() \ No newline at end of file +test() diff --git a/docs/examples/node/websocketexample/stmt_example.js b/docs/examples/node/websocketexample/stmt_example.js index d159de6ef8..6ca4959c48 100644 --- a/docs/examples/node/websocketexample/stmt_example.js +++ b/docs/examples/node/websocketexample/stmt_example.js @@ -3,7 +3,7 @@ const taos = require("@tdengine/websocket"); let db = 'power'; let stable = 'meters'; let numOfSubTable = 10; -let numOfRow = 10; +let numOfRow = 10; let dsn = 'ws://localhost:6041' function getRandomInt(min, max) { min = Math.ceil(min); @@ -59,7 +59,7 @@ async function prepare() { } } catch (err) { - console.error("Failed to insert to table meters using stmt, url:" + dsn + "ErrCode:" + err.code + "; ErrMessage: " + err.message); + console.error("Failed to insert to table meters using stmt, ErrCode: " + err.code + ", ErrMessage: " + err.message); } finally { if (stmt) { diff --git a/docs/examples/node/websocketexample/tmq_example.js b/docs/examples/node/websocketexample/tmq_example.js index ff676fa972..b0e52360c9 100644 --- a/docs/examples/node/websocketexample/tmq_example.js +++ b/docs/examples/node/websocketexample/tmq_example.js @@ -23,11 +23,11 @@ async function createConsumer() { conn = await taos.tmqConnect(configMap); console.log(`Create consumer successfully, host: ${url}, groupId: ${groupId}, clientId: ${clientId}`) return conn; - }catch (err) { - console.log("Failed to create websocket consumer, ErrCode:" + err.code + "; ErrMessage: " + err.message); + } catch (err) { + console.log("Failed to create websocket consumer, ErrCode:" + err.code + ", ErrMessage: " + err.message); throw err; } - + } // ANCHOR_END: create_consumer @@ -38,7 +38,7 @@ async function prepare() { conf.setDb('power'); const createDB = `CREATE DATABASE IF NOT EXISTS ${db}`; const createStable = `CREATE STABLE IF NOT EXISTS ${db}.${stable} (ts timestamp, current float, voltage int, phase float) TAGS (location binary(64), groupId int);`; - + let wsSql = await taos.sqlConnect(conf); await wsSql.exec(createDB); await wsSql.exec(createStable); @@ -64,9 +64,9 @@ async function subscribe(consumer) { } consumer.commit(); console.log("Commit offset manually successfully."); - } + } } catch (err) { - console.error("Failed to poll data; ErrCode:" + err.code + "; ErrMessage: " + err.message); + console.error("Failed to poll data, ErrCode: " + err.code + ", ErrMessage: " + err.message); throw err; } // ANCHOR_END: commit @@ -78,16 +78,17 @@ async function test() { try { await prepare(); let consumer = await createConsumer() - await subscribe(consumer) + await subscribe(consumer) await consumer.unsubscribe(); console.log("Consumer unsubscribed successfully."); } catch (err) { - console.error("Failed to unsubscribe consume, ErrCode:" + err.code + "; ErrMessage: " + err.message); + console.error("Failed to unsubscribe consumer, ErrCode: " + err.code + ", ErrMessage: " + err.message); } finally { if (consumer) { await consumer.close(); + console.log("Consumer closed successfully."); } taos.destroy(); } diff --git a/docs/examples/node/websocketexample/tmq_seek_example.js b/docs/examples/node/websocketexample/tmq_seek_example.js index da22217e14..0dea7e1671 100644 --- a/docs/examples/node/websocketexample/tmq_seek_example.js +++ b/docs/examples/node/websocketexample/tmq_seek_example.js @@ -59,7 +59,7 @@ async function subscribe(consumer) { } } } catch (err) { - console.error("Failed to poll data; ErrCode:" + err.code + "; ErrMessage: " + err.message); + console.error("Failed to poll data, ErrCode: " + err.code + ", ErrMessage: " + err.message); throw err; } @@ -83,7 +83,7 @@ async function test() { console.log("Assignment seek to beginning successfully"); } catch (err) { - console.error("Seek example failed, ErrCode:" + err.code + "; ErrMessage: " + err.message); + console.error("Failed to execute seek example, ErrCode: " + err.code + ", ErrMessage: " + err.message); } finally { if (consumer) { diff --git a/docs/examples/python/connect_example.py b/docs/examples/python/connect_example.py index 1f01a04e4c..ce8b306024 100644 --- a/docs/examples/python/connect_example.py +++ b/docs/examples/python/connect_example.py @@ -14,11 +14,11 @@ def create_connection(): ) print(f"Connected to {host}:{port} successfully."); except Exception as err: - print(f"Failed to connect to {host}:{port} ; ErrMessage:{err}") + print(f"Failed to connect to {host}:{port} , ErrMessage:{err}") finally: if conn: conn.close() if __name__ == "__main__": - create_connection() \ No newline at end of file + create_connection() diff --git a/docs/examples/python/connect_rest_example.py b/docs/examples/python/connect_rest_example.py index bd65ce7970..02daa60b2e 100644 --- a/docs/examples/python/connect_rest_example.py +++ b/docs/examples/python/connect_rest_example.py @@ -12,7 +12,7 @@ def create_connection(): print(f"Connected to {url} successfully."); except Exception as err: - print(f"Failed to connect to {url} ; ErrMessage:{err}") + print(f"Failed to connect to {url} , ErrMessage:{err}") finally: if conn: conn.close() diff --git a/docs/examples/python/connect_websocket_examples.py b/docs/examples/python/connect_websocket_examples.py index 79e96dd09c..56d208f5db 100644 --- a/docs/examples/python/connect_websocket_examples.py +++ b/docs/examples/python/connect_websocket_examples.py @@ -14,7 +14,7 @@ def create_connection(): ) print(f"Connected to {host}:{port} successfully."); except Exception as err: - print(f"Failed to connect to {host}:{port} ; ErrMessage:{err}") + print(f"Failed to connect to {host}:{port} , ErrMessage:{err}") return conn # ANCHOR_END: connect diff --git a/docs/examples/python/create_db_native.py b/docs/examples/python/create_db_native.py index 1a98a242f2..34dabfabe2 100644 --- a/docs/examples/python/create_db_native.py +++ b/docs/examples/python/create_db_native.py @@ -20,7 +20,7 @@ try: print(f"Create stable power.meters successfully, rowsAffected: {rowsAffected}"); except Exception as err: - print(f"Failed to create db and table, db addr:{host}:{port} ; ErrMessage:{err}") + print(f"Failed to create database power or stable meters, ErrMessage:{err}") finally: if conn: conn.close() diff --git a/docs/examples/python/create_db_rest.py b/docs/examples/python/create_db_rest.py index 2387b80195..4b98c991a3 100644 --- a/docs/examples/python/create_db_rest.py +++ b/docs/examples/python/create_db_rest.py @@ -19,7 +19,7 @@ try: print(f"Create stable power.meters successfully, rowsAffected: {rowsAffected}"); except Exception as err: - print(f"Failed to create db and table, url:{url} ; ErrMessage:{err}") + print(f"Failed to create database power or stable meters, ErrMessage:{err}") finally: if conn: conn.close() diff --git a/docs/examples/python/create_db_ws.py b/docs/examples/python/create_db_ws.py index 7749ba617f..ddbacb4b1f 100644 --- a/docs/examples/python/create_db_ws.py +++ b/docs/examples/python/create_db_ws.py @@ -20,7 +20,7 @@ try: print(f"Create stable power.meters successfully, rowsAffected: {rowsAffected}"); except Exception as err: - print(f"Failed to create db and table, db addrr:{host}:{port} ; ErrMessage:{err}") + print(f"Failed to create database power or stable meters, ErrMessage:{err}") finally: if conn: conn.close() diff --git a/docs/examples/python/insert_native.py b/docs/examples/python/insert_native.py index 5f1b6fbc21..ad7a8b85c2 100644 --- a/docs/examples/python/insert_native.py +++ b/docs/examples/python/insert_native.py @@ -21,7 +21,7 @@ try: print(f"Successfully inserted {affectedRows} rows to power.meters.") except Exception as err: - print(f"Failed to insert data to power.meters, db addr:{host}:{port} ; ErrMessage:{err}") + print(f"Failed to insert data to power.meters, ErrMessage:{err}") finally: if conn: conn.close() diff --git a/docs/examples/python/insert_rest.py b/docs/examples/python/insert_rest.py index d8e07323a9..41fd70857f 100644 --- a/docs/examples/python/insert_rest.py +++ b/docs/examples/python/insert_rest.py @@ -20,7 +20,7 @@ try: print(f"Successfully inserted {affectedRows} rows to power.meters.") except Exception as err: - print(f"Failed to insert data to power.meters, url:{url} ; ErrMessage:{err}") + print(f"Failed to insert data to power.meters, ErrMessage:{err}") finally: if conn: conn.close() diff --git a/docs/examples/python/insert_ws.py b/docs/examples/python/insert_ws.py index 0e1f74e2cf..9c03b4857a 100644 --- a/docs/examples/python/insert_ws.py +++ b/docs/examples/python/insert_ws.py @@ -21,7 +21,7 @@ try: print(f"Successfully inserted {affectedRows} rows to power.meters.") except Exception as err: - print(f"Failed to insert data to power.meters, db addr:{host}:{port} ; ErrMessage:{err}") + print(f"Failed to insert data to power.meters, ErrMessage:{err}") finally: if conn: conn.close() diff --git a/docs/examples/python/query_native.py b/docs/examples/python/query_native.py index df19819de7..072807986e 100644 --- a/docs/examples/python/query_native.py +++ b/docs/examples/python/query_native.py @@ -7,15 +7,15 @@ try: port=port, user="root", password="taosdata") - - result = conn.query("SELECT ts, current, location FROM power.meters limit 100") + sql = "SELECT ts, current, location FROM power.meters limit 100" + result = conn.query(sql) # Get data from result as list of tuple data = result.fetch_all() for row in data: print(f"ts: {row[0]}, current: {row[1]}, location: {row[2]}") except Exception as err: - print(f"Failed to query data from power.meters, db addr:{host}:{port} ; ErrMessage:{err}") + print(f"Failed to query data from power.meters, sql: {sql}, ErrMessage:{err}") finally: if conn: - conn.close() \ No newline at end of file + conn.close() diff --git a/docs/examples/python/query_rest.py b/docs/examples/python/query_rest.py index de16ace8be..85a70fd382 100644 --- a/docs/examples/python/query_rest.py +++ b/docs/examples/python/query_rest.py @@ -7,11 +7,11 @@ try: user="root", password="taosdata", timeout=30) - - result = client.sql(f"SELECT ts, current, location FROM power.meters limit 100") + sql = f"SELECT ts, current, location FROM power.meters limit 100" + result = client.sql(sql) if result["data"]: for row in result["data"]: print(f"ts: {row[0]}, current: {row[1]}, location: {row[2]}") except Exception as err: - print(f"Failed to query data from power.meters, url:{url} ; ErrMessage:{err}") + print(f"Failed to query data from power.meters, sql: {sql}, ErrMessage:{err}") diff --git a/docs/examples/python/query_ws.py b/docs/examples/python/query_ws.py index 8d177b167a..afab438ad9 100644 --- a/docs/examples/python/query_ws.py +++ b/docs/examples/python/query_ws.py @@ -8,13 +8,13 @@ try: password="taosdata", host=host, port=port) - - result = conn.query("SELECT ts, current, location FROM power.meters limit 100") + sql = "SELECT ts, current, location FROM power.meters limit 100" + result = conn.query(sql) for row in result: print(f"ts: {row[0]}, current: {row[1]}, location: {row[2]}") except Exception as err: - print(f"Failed to query data from power.meters, db addr:{host}:{port} ; ErrMessage:{err}") + print(f"Failed to query data from power.meters, sql: {sql}, ErrMessage:{err}") finally: if conn: conn.close() diff --git a/docs/examples/python/reqid_native.py b/docs/examples/python/reqid_native.py index 8f5bb3538c..7f16093835 100644 --- a/docs/examples/python/reqid_native.py +++ b/docs/examples/python/reqid_native.py @@ -17,7 +17,7 @@ try: print(f"ts: {row[0]}, current: {row[1]}, location: {row[2]}") except Exception as err: - print(f"Failed to execute sql with reqId:{reqId}, db addr:{host}:{port} ; ErrMessage:{err}") + print(f"Failed to execute sql with reqId:{reqId}, ErrMessage:{err}") finally: if conn: diff --git a/docs/examples/python/reqid_rest.py b/docs/examples/python/reqid_rest.py index 76ba735234..570e671092 100644 --- a/docs/examples/python/reqid_rest.py +++ b/docs/examples/python/reqid_rest.py @@ -15,4 +15,4 @@ try: print(f"ts: {row[0]}, current: {row[1]}, location: {row[2]}") except Exception as err: - print(f"Failed to execute sql with reqId:{reqId}, url:{url} ; ErrMessage:{err}") + print(f"Failed to execute sql with reqId:{reqId}, ErrMessage:{err}") diff --git a/docs/examples/python/reqid_ws.py b/docs/examples/python/reqid_ws.py index 691dde710f..7c74104169 100644 --- a/docs/examples/python/reqid_ws.py +++ b/docs/examples/python/reqid_ws.py @@ -18,7 +18,7 @@ try: print(f"ts: {row[0]}, current: {row[1]}, location: {row[2]}") except Exception as err: - print(f"Failed to execute sql with reqId:{reqId}, db addr:{host}:{port} ; ErrMessage:{err}") + print(f"Failed to execute sql with reqId:{reqId}, ErrMessage:{err}") finally: if conn: conn.close() diff --git a/docs/examples/python/schemaless_native.py b/docs/examples/python/schemaless_native.py index 0cb4d1c94d..96d8f3177f 100644 --- a/docs/examples/python/schemaless_native.py +++ b/docs/examples/python/schemaless_native.py @@ -34,7 +34,7 @@ try: ) print("Inserted data with schemaless successfully."); except Exception as err: - print(f"Failed to insert data with schemaless, addr: {host}:{port} ErrMessage:{err}") + print(f"Failed to insert data with schemaless, ErrMessage:{err}") finally: if conn: conn.close() diff --git a/docs/examples/python/schemaless_ws.py b/docs/examples/python/schemaless_ws.py index f03f78b10f..3c41d1768b 100644 --- a/docs/examples/python/schemaless_ws.py +++ b/docs/examples/python/schemaless_ws.py @@ -66,7 +66,7 @@ def schemaless_insert(): ) print("Inserted data with schemaless successfully."); except Exception as err: - print(f"Failed to insert data with schemaless, addr: {host}:{port} ErrMessage:{err}") + print(f"Failed to insert data with schemaless, ErrMessage:{err}") raise err finally: @@ -78,4 +78,4 @@ if __name__ == "__main__": prepare() schemaless_insert except Exception as err: - print(f"Failed to insert data with schemaless, err:{err}") \ No newline at end of file + print(f"Failed to insert data with schemaless, err:{err}") diff --git a/docs/examples/python/stmt_native.py b/docs/examples/python/stmt_native.py index ea0cf9c626..16975d6895 100644 --- a/docs/examples/python/stmt_native.py +++ b/docs/examples/python/stmt_native.py @@ -56,7 +56,7 @@ try: print(f"Successfully inserted to power.meters.") except Exception as err: - print(f"Failed to insert to table meters using stmt, addr:{host}:{port} ; ErrMessage:{err}") + print(f"Failed to insert to table meters using stmt, ErrMessage:{err}") finally: if stmt: stmt.close() diff --git a/docs/examples/python/stmt_ws.py b/docs/examples/python/stmt_ws.py index 8d992b32e6..74f071fde1 100644 --- a/docs/examples/python/stmt_ws.py +++ b/docs/examples/python/stmt_ws.py @@ -61,7 +61,7 @@ try: print(f"Successfully inserted to power.meters.") except Exception as err: - print(f"Failed to insert to table meters using stmt, addr:{host}:{port} ; ErrMessage:{err}") + print(f"Failed to insert to table meters using stmt, ErrMessage:{err}") finally: if stmt: stmt.close() diff --git a/docs/examples/python/tmq_native.py b/docs/examples/python/tmq_native.py index 64e447384c..bed173c506 100644 --- a/docs/examples/python/tmq_native.py +++ b/docs/examples/python/tmq_native.py @@ -70,7 +70,7 @@ def create_consumer(): print(f"Create consumer successfully, host: {host}:{port}, groupId: {groupId}, clientId: {clientId}"); return consumer except Exception as err: - print(f"Failed to create native consumer, host: {host}:{port} ; ErrMessage:{err}"); + print(f"Failed to create native consumer, host: {host}:{port}, ErrMessage:{err}"); raise err # ANCHOR_END: create_consumer @@ -123,7 +123,7 @@ def commit_offset(consumer): print("Commit offset manually successfully."); except Exception as err: - print(f"Failed to poll data, ErrMessage:{err}") + print(f"Failed to execute commit example, ErrMessage:{err}") raise err # ANCHOR_END: commit_offset @@ -138,7 +138,7 @@ def seek_offset(consumer): consumer.seek(partition) print(f"Assignment seek to beginning successfully"); except Exception as err: - print(f"Seek example failed; ErrMessage:{err}") + print(f"Failed to execute seek example, ErrMessage:{err}") raise err # ANCHOR_END: assignment @@ -151,7 +151,8 @@ def unsubscribe(consumer): print(f"Failed to unsubscribe consumer. ErrMessage:{err}") finally: if consumer: - consumer.close() + consumer.close() + print("Consumer closed successfully."); # ANCHOR_END: unsubscribe if __name__ == "__main__": @@ -165,7 +166,7 @@ if __name__ == "__main__": consumer.unsubscribe() print("Consumer unsubscribed successfully."); except Exception as err: - print(f"Failed to stmt consumer. ErrMessage:{err}") + print(f"Failed to execute consumer example, ErrMessage:{err}") finally: consumer.unsubscribe() diff --git a/docs/examples/python/tmq_websocket_example.py b/docs/examples/python/tmq_websocket_example.py index aa9cbf6545..15441fbb41 100644 --- a/docs/examples/python/tmq_websocket_example.py +++ b/docs/examples/python/tmq_websocket_example.py @@ -78,7 +78,7 @@ def create_consumer(): print(f"Create consumer successfully, host: {host}:{port}, groupId: {groupId}, clientId: {clientId}"); return consumer; except Exception as err: - print(f"Failed to create websocket consumer, host: {host}:{port} ; ErrMessage:{err}"); + print(f"Failed to create websocket consumer, host: {host}:{port}, ErrMessage:{err}"); raise err @@ -98,7 +98,7 @@ def seek_offset(consumer): print("Assignment seek to beginning successfully"); except Exception as err: - print(f"Seek example failed; ErrMessage:{err}") + print(f"Failed to execute seek example, ErrMessage:{err}") raise err # ANCHOR_END: assignment @@ -137,7 +137,7 @@ def commit_offset(consumer): print("Commit offset manually successfully."); except Exception as err: - print(f"Failed to poll data, ErrMessage:{err}") + print(f"Failed to execute commit example, ErrMessage:{err}") raise err @@ -153,7 +153,8 @@ def unsubscribe(consumer): print(f"Failed to unsubscribe consumer. ErrMessage:{err}") finally: if consumer: - consumer.close() + consumer.close() + print("Consumer closed successfully."); # ANCHOR_END: unsubscribe @@ -166,6 +167,6 @@ if __name__ == "__main__": seek_offset(consumer) commit_offset(consumer) except Exception as err: - print(f"Failed to stmt consumer. ErrorMessage:{err}") + print(f"Failed to execute consumer example, ErrorMessage:{err}") finally: - unsubscribe(consumer); \ No newline at end of file + unsubscribe(consumer); diff --git a/docs/examples/rust/nativeexample/examples/connect.rs b/docs/examples/rust/nativeexample/examples/connect.rs index 7da09ae7ec..ad2533d4c3 100644 --- a/docs/examples/rust/nativeexample/examples/connect.rs +++ b/docs/examples/rust/nativeexample/examples/connect.rs @@ -10,7 +10,7 @@ async fn main() -> anyhow::Result<()> { Ok(()) } Err(err) => { - eprintln!("Failed to connect to {}; ErrMessage: {}", dsn, err); + eprintln!("Failed to connect to {}, ErrMessage: {}", dsn, err); return Err(err.into()); } } diff --git a/docs/examples/rust/nativeexample/examples/createdb.rs b/docs/examples/rust/nativeexample/examples/createdb.rs index d3b2f5178b..292f13de8f 100644 --- a/docs/examples/rust/nativeexample/examples/createdb.rs +++ b/docs/examples/rust/nativeexample/examples/createdb.rs @@ -13,7 +13,7 @@ async fn main() -> anyhow::Result<()> { ]).await { Ok(afffected_rows) => println!("Create database power successfully, rowsAffected: {}", afffected_rows), Err(err) => { - eprintln!("Failed to create database power; ErrMessage: {}", err); + eprintln!("Failed to create database power, ErrMessage: {}", err); return Err(err.into()); } } @@ -25,7 +25,7 @@ async fn main() -> anyhow::Result<()> { ]).await { Ok(afffected_rows) => println!("Create stable power.meters successfully, rowsAffected: {}", afffected_rows), Err(err) => { - eprintln!("Failed to create stable power.meters; ErrMessage: {}", err); + eprintln!("Failed to create stable power.meters, ErrMessage: {}", err); return Err(err.into()); } } diff --git a/docs/examples/rust/nativeexample/examples/insert.rs b/docs/examples/rust/nativeexample/examples/insert.rs index d551da436e..e78381fc61 100644 --- a/docs/examples/rust/nativeexample/examples/insert.rs +++ b/docs/examples/rust/nativeexample/examples/insert.rs @@ -20,7 +20,7 @@ async fn main() -> anyhow::Result<()> { (NOW + 1a, 10.30000, 218, 0.25000) "#).await{ Ok(affected_rows) => println!("Successfully inserted {} rows to power.meters.", affected_rows), Err(err) => { - eprintln!("Failed to insert data to power.meters, dsn: {}; ErrMessage: {}", dsn, err); + eprintln!("Failed to insert data to power.meters, ErrMessage: {}", err); return Err(err.into()); } } diff --git a/docs/examples/rust/nativeexample/examples/query.rs b/docs/examples/rust/nativeexample/examples/query.rs index 6b6fde6a31..e4f7c45521 100644 --- a/docs/examples/rust/nativeexample/examples/query.rs +++ b/docs/examples/rust/nativeexample/examples/query.rs @@ -11,7 +11,8 @@ async fn main() -> anyhow::Result<()> { // ANCHOR: query_data // query data, make sure the database and table are created before - match taos.query("SELECT ts, current, location FROM power.meters limit 100").await{ + let sql = "SELECT ts, current, location FROM power.meters limit 100"; + match taos.query(sql).await{ Ok(mut result) => { for field in result.fields() { println!("got field: {}", field.name()); @@ -30,7 +31,7 @@ async fn main() -> anyhow::Result<()> { } } Err(err) => { - eprintln!("Failed to query data from power.meters, dsn: {}; ErrMessage: {}", dsn, err); + eprintln!("Failed to query data from power.meters, sql: {}, ErrMessage: {}", sql, err); return Err(err.into()); } } @@ -51,6 +52,7 @@ async fn main() -> anyhow::Result<()> { location: String, } + let sql = "SELECT ts, current, location FROM power.meters limit 100"; match taos.query("SELECT ts, current, location FROM power.meters limit 100").await { Ok(mut query) => { match query.deserialize::().try_collect::>().await { @@ -64,7 +66,7 @@ async fn main() -> anyhow::Result<()> { } } Err(err) => { - eprintln!("Failed to query data from power.meters, url: {}; ErrMessage: {}", dsn, err); + eprintln!("Failed to query data from power.meters, sql: {}, ErrMessage: {}", sql, err); return Err(err.into()); } } @@ -92,7 +94,7 @@ async fn main() -> anyhow::Result<()> { } } Err(err) => { - eprintln!("Failed to execute sql with reqId: {}, dsn: {}; ErrMessage: {}", req_id, dsn, err); + eprintln!("Failed to execute sql with reqId: {}, ErrMessage: {}", req_id, err); return Err(err.into()); } } diff --git a/docs/examples/rust/nativeexample/examples/schemaless.rs b/docs/examples/rust/nativeexample/examples/schemaless.rs index 88e9ef4584..75f806f54c 100644 --- a/docs/examples/rust/nativeexample/examples/schemaless.rs +++ b/docs/examples/rust/nativeexample/examples/schemaless.rs @@ -43,7 +43,7 @@ async fn main() -> anyhow::Result<()> { match client.put(&sml_data).await{ Ok(_) => {}, Err(err) => { - eprintln!("Failed to insert data with schemaless, host: {}; ErrMessage: {}", host, err); + eprintln!("Failed to insert data with schemaless, data:{:?}, ErrMessage: {}", data, err); return Err(err.into()); } } @@ -65,7 +65,7 @@ async fn main() -> anyhow::Result<()> { match client.put(&sml_data).await{ Ok(_) => {}, Err(err) => { - eprintln!("Failed to insert data with schemaless, host: {}; ErrMessage: {}", host, err); + eprintln!("Failed to insert data with schemaless, data:{:?}, ErrMessage: {}", data, err); return Err(err.into()); } } @@ -96,7 +96,7 @@ async fn main() -> anyhow::Result<()> { match client.put(&sml_data).await{ Ok(_) => {}, Err(err) => { - eprintln!("Failed to insert data with schemaless, host: {}; ErrMessage: {}", host, err); + eprintln!("Failed to insert data with schemaless, data:{:?}, ErrMessage: {}", data, err); return Err(err.into()); } } diff --git a/docs/examples/rust/nativeexample/examples/stmt.rs b/docs/examples/rust/nativeexample/examples/stmt.rs index de35ae2972..0091283a6b 100644 --- a/docs/examples/rust/nativeexample/examples/stmt.rs +++ b/docs/examples/rust/nativeexample/examples/stmt.rs @@ -20,7 +20,13 @@ async fn main() -> anyhow::Result<()> { let tags = vec![Value::Int(i as i32), Value::VarChar(format!("location_{}", i).into())]; // set table name and tags for the prepared statement. - stmt.set_tbname_tags(&table_name, &tags).await?; + match stmt.set_tbname_tags(&table_name, &tags).await{ + Ok(_) => {}, + Err(err) => { + eprintln!("Failed to set table name and tags, table_name:{}, tags:{:?}, ErrMessage: {}", table_name, tags, err); + return Err(err.into()); + } + } for j in 0..NUM_ROWS { let values = vec![ ColumnView::from_millis_timestamp(vec![1648432611249 + j as i64]), @@ -29,17 +35,29 @@ async fn main() -> anyhow::Result<()> { ColumnView::from_floats(vec![0.31 + j as f32]), ]; // bind values to the prepared statement. - stmt.bind(&values).await?; + match stmt.bind(&values).await{ + Ok(_) => {}, + Err(err) => { + eprintln!("Failed to bind values, values:{:?}, ErrMessage: {}", values, err); + return Err(err.into()); + } + } } - stmt.add_batch().await?; + match stmt.add_batch().await{ + Ok(_) => {}, + Err(err) => { + eprintln!("Failed to add batch, ErrMessage: {}", err); + return Err(err.into()); + } + } } // execute. match stmt.execute().await{ Ok(affected_rows) => println!("Successfully inserted {} rows to power.meters.", affected_rows), Err(err) => { - eprintln!("Failed to insert to table meters using stmt, dsn: {}; ErrMessage: {}", dsn, err); + eprintln!("Failed to insert to table meters using stmt, ErrMessage: {}", err); return Err(err.into()); } } diff --git a/docs/examples/rust/nativeexample/examples/tmq.rs b/docs/examples/rust/nativeexample/examples/tmq.rs index 7f3bd416d1..f312bee0f2 100644 --- a/docs/examples/rust/nativeexample/examples/tmq.rs +++ b/docs/examples/rust/nativeexample/examples/tmq.rs @@ -53,7 +53,7 @@ async fn main() -> anyhow::Result<()> { consumer } Err(err) => { - eprintln!("Failed to create consumer, dsn: {}; ErrMessage: {}", dsn, err); + eprintln!("Failed to create websocket consumer, dsn: {}, ErrMessage: {}", dsn, err); return Err(err.into()); } }; @@ -63,7 +63,7 @@ async fn main() -> anyhow::Result<()> { match consumer.subscribe(["topic_meters"]).await{ Ok(_) => println!("Subscribe topics successfully."), Err(err) => { - eprintln!("Failed to subscribe topic_meters, dsn: {}; ErrMessage: {}", dsn, err); + eprintln!("Failed to subscribe topic_meters, ErrMessage: {}", err); return Err(err.into()); } } @@ -100,7 +100,7 @@ async fn main() -> anyhow::Result<()> { Ok(()) }) .await.map_err(|e| { - eprintln!("Failed to execute consumer functions. ErrMessage: {:?}", e); + eprintln!("Failed to poll data; ErrMessage: {:?}", e); e })?; @@ -125,14 +125,14 @@ async fn main() -> anyhow::Result<()> { match consumer.commit(offset).await{ Ok(_) => println!("Commit offset manually successfully."), Err(err) => { - eprintln!("Failed to commit offset manually, dsn: {}; ErrMessage: {}", dsn, err); + eprintln!("Failed to commit offset manually, ErrMessage: {}", err); return Err(err.into()); } } Ok(()) }) .await.map_err(|e| { - eprintln!("Failed to execute consumer functions. ErrMessage: {:?}", e); + eprintln!("Failed to poll data, ErrMessage: {:?}", e); e })?; // ANCHOR_END: consumer_commit_manually @@ -140,7 +140,7 @@ async fn main() -> anyhow::Result<()> { // ANCHOR: seek_offset let assignments = consumer.assignments().await.unwrap(); - println!("Now assignments: {:?}", assignments); + println!("assignments: {:?}", assignments); // seek offset for topic_vec_assignment in assignments { @@ -163,14 +163,14 @@ async fn main() -> anyhow::Result<()> { match consumer.offset_seek(topic, vgroup_id, begin).await{ Ok(_) => (), Err(err) => { - eprintln!("Seek example failed; ErrMessage: {}", err); + eprintln!("Failed to seek offset, ErrMessage: {}", err); return Err(err.into()); } } } let topic_assignment = consumer.topic_assignment(topic).await; - println!("Topic assignment: {:?}", topic_assignment); + println!("topic assignment: {:?}", topic_assignment); } println!("Assignment seek to beginning successfully."); // after seek offset diff --git a/docs/examples/rust/restexample/examples/connect.rs b/docs/examples/rust/restexample/examples/connect.rs index 535e265a97..7051572296 100644 --- a/docs/examples/rust/restexample/examples/connect.rs +++ b/docs/examples/rust/restexample/examples/connect.rs @@ -10,7 +10,7 @@ async fn main() -> anyhow::Result<()> { Ok(()) } Err(err) => { - eprintln!("Failed to connect to {}; ErrMessage: {}", dsn, err); + eprintln!("Failed to connect to {}, ErrMessage: {}", dsn, err); return Err(err.into()); } } diff --git a/docs/examples/rust/restexample/examples/createdb.rs b/docs/examples/rust/restexample/examples/createdb.rs index e061f1d835..896868ae15 100644 --- a/docs/examples/rust/restexample/examples/createdb.rs +++ b/docs/examples/rust/restexample/examples/createdb.rs @@ -13,7 +13,7 @@ async fn main() -> anyhow::Result<()> { ]).await { Ok(afffected_rows) => println!("Create database power successfully, rowsAffected: {}", afffected_rows), Err(err) => { - eprintln!("Failed to create database power; ErrMessage: {}", err); + eprintln!("Failed to create database power, ErrMessage: {}", err); return Err(err.into()); } } @@ -25,7 +25,7 @@ async fn main() -> anyhow::Result<()> { ]).await { Ok(afffected_rows) => println!("Create stable power.meters successfully, rowsAffected: {}", afffected_rows), Err(err) => { - eprintln!("Failed to create stable power.meters; ErrMessage: {}", err); + eprintln!("Failed to create stable power.meters, ErrMessage: {}", err); return Err(err.into()); } } diff --git a/docs/examples/rust/restexample/examples/insert.rs b/docs/examples/rust/restexample/examples/insert.rs index 62522575ee..537e531501 100644 --- a/docs/examples/rust/restexample/examples/insert.rs +++ b/docs/examples/rust/restexample/examples/insert.rs @@ -20,7 +20,7 @@ async fn main() -> anyhow::Result<()> { (NOW + 1a, 10.30000, 218, 0.25000) "#).await{ Ok(affected_rows) => println!("Successfully inserted {} rows to power.meters.", affected_rows), Err(err) => { - eprintln!("Failed to insert data to power.meters, dsn: {}; ErrMessage: {}", dsn, err); + eprintln!("Failed to insert data to power.meters, ErrMessage: {}", dsn, err); return Err(err.into()); } } diff --git a/docs/examples/rust/restexample/examples/query.rs b/docs/examples/rust/restexample/examples/query.rs index 4e69f9fc97..4366efd265 100644 --- a/docs/examples/rust/restexample/examples/query.rs +++ b/docs/examples/rust/restexample/examples/query.rs @@ -11,7 +11,8 @@ async fn main() -> anyhow::Result<()> { // ANCHOR: query_data // query data, make sure the database and table are created before - match taos.query("SELECT ts, current, location FROM power.meters limit 100").await{ + let sql = "SELECT ts, current, location FROM power.meters limit 100"; + match taos.query(sql).await{ Ok(mut result) => { for field in result.fields() { println!("got field: {}", field.name()); @@ -30,7 +31,7 @@ async fn main() -> anyhow::Result<()> { } } Err(err) => { - eprintln!("Failed to query data from power.meters, dsn: {}; ErrMessage: {}", dsn, err); + eprintln!("Failed to query data from power.meters, sql: {}, ErrMessage: {}", sql, err); return Err(err.into()); } } @@ -51,6 +52,7 @@ async fn main() -> anyhow::Result<()> { location: String, } + let sql = "SELECT ts, current, location FROM power.meters limit 100"; match taos.query("SELECT ts, current, location FROM power.meters limit 100").await { Ok(mut query) => { match query.deserialize::().try_collect::>().await { @@ -64,7 +66,7 @@ async fn main() -> anyhow::Result<()> { } } Err(err) => { - eprintln!("Failed to query data from power.meters, url: {}; ErrMessage: {}", dsn, err); + eprintln!("Failed to query data from power.meters, sql: {}, ErrMessage: {}", sql, err); return Err(err.into()); } } @@ -92,7 +94,7 @@ async fn main() -> anyhow::Result<()> { } } Err(err) => { - eprintln!("Failed to execute sql with reqId: {}, dsn: {}; ErrMessage: {}", req_id, dsn, err); + eprintln!("Failed to execute sql with reqId: {}, ErrMessage: {}", req_id, err); return Err(err.into()); } } diff --git a/docs/examples/rust/restexample/examples/schemaless.rs b/docs/examples/rust/restexample/examples/schemaless.rs index f629d66663..fe666cca6f 100644 --- a/docs/examples/rust/restexample/examples/schemaless.rs +++ b/docs/examples/rust/restexample/examples/schemaless.rs @@ -17,6 +17,15 @@ async fn main() -> anyhow::Result<()> { let client = TaosBuilder::from_dsn(dsn)?.build().await?; + let db = "power"; + + client + .exec(format!("create database if not exists {db}")) + .await?; + + // should specify database before insert + client.exec(format!("use {db}")).await?; + // SchemalessProtocol::Line let data = [ "meters,groupid=2,location=California.SanFrancisco current=10.3000002f64,voltage=219i32,phase=0.31f64 1626006833639", @@ -34,7 +43,7 @@ async fn main() -> anyhow::Result<()> { match client.put(&sml_data).await{ Ok(_) => {}, Err(err) => { - eprintln!("Failed to insert data with schemaless, host: {}; ErrMessage: {}", host, err); + eprintln!("Failed to insert data with schemaless, data:{:?}, ErrMessage: {}", data, err); return Err(err.into()); } } @@ -56,7 +65,7 @@ async fn main() -> anyhow::Result<()> { match client.put(&sml_data).await{ Ok(_) => {}, Err(err) => { - eprintln!("Failed to insert data with schemaless, host: {}; ErrMessage: {}", host, err); + eprintln!("Failed to insert data with schemaless, data:{:?}, ErrMessage: {}", data, err); return Err(err.into()); } } @@ -87,7 +96,7 @@ async fn main() -> anyhow::Result<()> { match client.put(&sml_data).await{ Ok(_) => {}, Err(err) => { - eprintln!("Failed to insert data with schemaless, host: {}; ErrMessage: {}", host, err); + eprintln!("Failed to insert data with schemaless, data:{:?}, ErrMessage: {}", data, err); return Err(err.into()); } } diff --git a/docs/examples/rust/restexample/examples/stmt.rs b/docs/examples/rust/restexample/examples/stmt.rs index 636b6780cd..4c3d5fb759 100644 --- a/docs/examples/rust/restexample/examples/stmt.rs +++ b/docs/examples/rust/restexample/examples/stmt.rs @@ -20,7 +20,13 @@ async fn main() -> anyhow::Result<()> { let tags = vec![Value::Int(i as i32), Value::VarChar(format!("location_{}", i).into())]; // set table name and tags for the prepared statement. - stmt.set_tbname_tags(&table_name, &tags).await?; + match stmt.set_tbname_tags(&table_name, &tags).await{ + Ok(_) => {}, + Err(err) => { + eprintln!("Failed to set table name and tags, table_name:{}, tags:{:?}, ErrMessage: {}", table_name, tags, err); + return Err(err.into()); + } + } for j in 0..NUM_ROWS { let values = vec![ ColumnView::from_millis_timestamp(vec![1648432611249 + j as i64]), @@ -29,17 +35,29 @@ async fn main() -> anyhow::Result<()> { ColumnView::from_floats(vec![0.31 + j as f32]), ]; // bind values to the prepared statement. - stmt.bind(&values).await?; + match stmt.bind(&values).await{ + Ok(_) => {}, + Err(err) => { + eprintln!("Failed to bind values, values:{:?}, ErrMessage: {}", values, err); + return Err(err.into()); + } + } } - stmt.add_batch().await?; + match stmt.add_batch().await{ + Ok(_) => {}, + Err(err) => { + eprintln!("Failed to add batch, ErrMessage: {}", err); + return Err(err.into()); + } + } } // execute. match stmt.execute().await{ Ok(affected_rows) => println!("Successfully inserted {} rows to power.meters.", affected_rows), Err(err) => { - eprintln!("Failed to insert to table meters using stmt, dsn: {}; ErrMessage: {}", dsn, err); + eprintln!("Failed to insert to table meters using stmt, ErrMessage: {}", err); return Err(err.into()); } } diff --git a/docs/examples/rust/restexample/examples/tmq.rs b/docs/examples/rust/restexample/examples/tmq.rs index 2abc0a36da..0a0214d258 100644 --- a/docs/examples/rust/restexample/examples/tmq.rs +++ b/docs/examples/rust/restexample/examples/tmq.rs @@ -53,7 +53,7 @@ async fn main() -> anyhow::Result<()> { consumer } Err(err) => { - eprintln!("Failed to create consumer, dsn: {}; ErrMessage: {}", dsn, err); + eprintln!("Failed to create websocket consumer, dsn: {}, ErrMessage: {}", dsn, err); return Err(err.into()); } }; @@ -63,7 +63,7 @@ async fn main() -> anyhow::Result<()> { match consumer.subscribe(["topic_meters"]).await{ Ok(_) => println!("Subscribe topics successfully."), Err(err) => { - eprintln!("Failed to subscribe topic_meters, dsn: {}; ErrMessage: {}", dsn, err); + eprintln!("Failed to subscribe topic_meters, ErrMessage: {}", err); return Err(err.into()); } } @@ -125,14 +125,14 @@ async fn main() -> anyhow::Result<()> { match consumer.commit(offset).await{ Ok(_) => println!("Commit offset manually successfully."), Err(err) => { - eprintln!("Failed to commit offset manually, dsn: {}; ErrMessage: {}", dsn, err); + eprintln!("Failed to commit offset manually, ErrMessage: {}", err); return Err(err.into()); } } Ok(()) }) .await.map_err(|e| { - eprintln!("Failed to execute consumer functions. ErrMessage: {:?}", e); + eprintln!("Failed to poll data, ErrMessage: {:?}", e); e })?; // ANCHOR_END: consumer_commit_manually @@ -163,7 +163,7 @@ async fn main() -> anyhow::Result<()> { match consumer.offset_seek(topic, vgroup_id, begin).await{ Ok(_) => (), Err(err) => { - eprintln!("seek example failed; ErrMessage: {}", err); + eprintln!("Failed to seek offset, ErrMessage: {}", err); return Err(err.into()); } } diff --git a/docs/zh/08-develop/01-connect/index.md b/docs/zh/08-develop/01-connect/index.md index 755a9e7f74..280e31b2a6 100644 --- a/docs/zh/08-develop/01-connect/index.md +++ b/docs/zh/08-develop/01-connect/index.md @@ -544,7 +544,7 @@ C/C++ 语言连接器使用 `taos_connect()` 函数用于建立与 TDengine 数 使用示例如下: ```java -{{#include examples/JDBC/connectionPools/src/main/java/com/taosdata/example/HikariDemo.java:connection_pool}} +{{#include docs/examples/java/src/main/java/com/taos/example/HikariDemo.java:connection_pool}} ``` > 通过 HikariDataSource.getConnection() 获取连接后,使用完成后需要调用 close() 方法,实际上它并不会关闭连接,只是放回连接池中。 @@ -555,7 +555,7 @@ C/C++ 语言连接器使用 `taos_connect()` 函数用于建立与 TDengine 数 使用示例如下: ```java -{{#include examples/JDBC/connectionPools/src/main/java/com/taosdata/example/DruidDemo.java:connection_pool}} +{{#include docs/examples/java/src/main/java/com/taos/example/DruidDemo.java:connection_pool}} ``` > 更多 druid 使用问题请查看[官方说明](https://github.com/alibaba/druid)。 diff --git a/docs/zh/08-develop/02-sql.md b/docs/zh/08-develop/02-sql.md index 7e42e38949..be44458c5b 100644 --- a/docs/zh/08-develop/02-sql.md +++ b/docs/zh/08-develop/02-sql.md @@ -27,7 +27,7 @@ REST API:直接调用 `taosadapter` 提供的 REST API 接口,进行数据 ```java -{{#include examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcCreatDBDemo.java:create_db_and_table}} +{{#include docs/examples/java/src/main/java/com/taos/example/JdbcCreatDBDemo.java:create_db_and_table}} ``` @@ -98,7 +98,7 @@ curl --location -uroot:taosdata 'http://127.0.0.1:6041/rest/sql/power' \ ```java -{{#include examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcInsertDataDemo.java:insert_data}} +{{#include docs/examples/java/src/main/java/com/taos/example/JdbcInsertDataDemo.java:insert_data}} ``` **Note** @@ -170,7 +170,7 @@ curl --location -uroot:taosdata 'http://127.0.0.1:6041/rest/sql' \ ```java -{{#include examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcQueryDemo.java:query_data}} +{{#include docs/examples/java/src/main/java/com/taos/example/JdbcQueryDemo.java:query_data}} ``` **Note** 查询和操作关系型数据库一致,使用下标获取返回字段内容时从 1 开始,建议使用字段名称获取。 @@ -251,7 +251,7 @@ reqId 可用于请求链路追踪,reqId 就像分布式系统中的 traceId ```java -{{#include examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcReqIdDemo.java:with_reqid}} +{{#include docs/examples/java/src/main/java/com/taos/example/JdbcReqIdDemo.java:with_reqid}} ``` diff --git a/docs/zh/08-develop/04-schemaless.md b/docs/zh/08-develop/04-schemaless.md index 06dec726e9..130d012e8b 100644 --- a/docs/zh/08-develop/04-schemaless.md +++ b/docs/zh/08-develop/04-schemaless.md @@ -165,7 +165,7 @@ st,t1=3,t2=4,t3=t3 c1=3i64,c6="passit" 1626006833640000000 ```java -{{#include examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/SchemalessWsTest.java:schemaless}} +{{#include docs/examples/java/src/main/java/com/taos/example/SchemalessWsTest.java:schemaless}} ``` @@ -216,7 +216,7 @@ writer.write(lineDemo, SchemalessProtocolType.LINE, SchemalessTimestampType.NANO ```java -{{#include examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/SchemalessJniTest.java:schemaless}} +{{#include docs/examples/java/src/main/java/com/taos/example/SchemalessJniTest.java:schemaless}} ``` 执行带有 reqId 的无模式写入,最后一个参数 reqId 可用于请求链路追踪。 diff --git a/docs/zh/08-develop/05-stmt.md b/docs/zh/08-develop/05-stmt.md index 4b8dbbce9b..9dfd9f56e3 100644 --- a/docs/zh/08-develop/05-stmt.md +++ b/docs/zh/08-develop/05-stmt.md @@ -27,7 +27,7 @@ import TabItem from "@theme/TabItem"; ```java -{{#include examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WSParameterBindingBasicDemo.java:para_bind}} +{{#include docs/examples/java/src/main/java/com/taos/example/WSParameterBindingBasicDemo.java:para_bind}} ``` @@ -76,7 +76,7 @@ import TabItem from "@theme/TabItem"; ```java -{{#include examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ParameterBindingBasicDemo.java:para_bind}} +{{#include docs/examples/java/src/main/java/com/taos/example/ParameterBindingBasicDemo.java:para_bind}} ``` 这是一个[更详细的参数绑定示例](https://github.com/taosdata/TDengine/blob/main/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ParameterBindingFullDemo.java) diff --git a/docs/zh/08-develop/07-tmq.md b/docs/zh/08-develop/07-tmq.md index 0711ab9f28..aedc59d05b 100644 --- a/docs/zh/08-develop/07-tmq.md +++ b/docs/zh/08-develop/07-tmq.md @@ -109,7 +109,7 @@ Rust 连接器创建消费者的参数为 DSN, 可以设置的参数列表请 ```java -{{#include examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WsConsumerLoopFull.java:create_consumer}} +{{#include docs/examples/java/src/main/java/com/taos/example/WsConsumerLoopFull.java:create_consumer}} ``` @@ -168,7 +168,7 @@ Rust 连接器创建消费者的参数为 DSN, 可以设置的参数列表请 ```java -{{#include examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ConsumerLoopFull.java:create_consumer}} +{{#include docs/examples/java/src/main/java/com/taos/example/ConsumerLoopFull.java:create_consumer}} ``` @@ -229,7 +229,7 @@ Rust 连接器创建消费者的参数为 DSN, 可以设置的参数列表请 ```java -{{#include examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WsConsumerLoopFull.java:poll_data_code_piece}} +{{#include docs/examples/java/src/main/java/com/taos/example/WsConsumerLoopFull.java:poll_data_code_piece}} ``` - `subscribe` 方法的参数含义为:订阅的主题列表(即名称),支持同时订阅多个主题。 @@ -293,7 +293,7 @@ Rust 连接器创建消费者的参数为 DSN, 可以设置的参数列表请 ```java -{{#include examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WsConsumerLoopFull.java:poll_data_code_piece}} +{{#include docs/examples/java/src/main/java/com/taos/example/WsConsumerLoopFull.java:poll_data_code_piece}} ``` - `subscribe` 方法的参数含义为:订阅的主题列表(即名称),支持同时订阅多个主题。 @@ -376,7 +376,7 @@ Rust 连接器创建消费者的参数为 DSN, 可以设置的参数列表请 ```java -{{#include examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WsConsumerLoopFull.java:consumer_seek}} +{{#include docs/examples/java/src/main/java/com/taos/example/WsConsumerLoopFull.java:consumer_seek}} ``` 1. 使用 consumer.poll 方法轮询数据,直到获取到数据为止。 2. 对于轮询到的第一批数据,打印第一条数据的内容,并获取当前消费者的分区分配信息。 @@ -438,7 +438,7 @@ Rust 连接器创建消费者的参数为 DSN, 可以设置的参数列表请 ```java -{{#include examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WsConsumerLoopFull.java:consumer_seek}} +{{#include docs/examples/java/src/main/java/com/taos/example/WsConsumerLoopFull.java:consumer_seek}} ``` 1. 使用 consumer.poll 方法轮询数据,直到获取到数据为止。 2. 对于轮询到的第一批数据,打印第一条数据的内容,并获取当前消费者的分区分配信息。 @@ -513,7 +513,7 @@ Rust 连接器创建消费者的参数为 DSN, 可以设置的参数列表请 ```java -{{#include examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WsConsumerLoopFull.java:commit_code_piece}} +{{#include docs/examples/java/src/main/java/com/taos/example/WsConsumerLoopFull.java:commit_code_piece}} ``` @@ -565,7 +565,7 @@ Rust 连接器创建消费者的参数为 DSN, 可以设置的参数列表请 ```java -{{#include examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WsConsumerLoopFull.java:commit_code_piece}} +{{#include docs/examples/java/src/main/java/com/taos/example/WsConsumerLoopFull.java:commit_code_piece}} ``` @@ -621,7 +621,7 @@ Rust 连接器创建消费者的参数为 DSN, 可以设置的参数列表请 ```java -{{#include examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WsConsumerLoopFull.java:unsubscribe_data_code_piece}} +{{#include docs/examples/java/src/main/java/com/taos/example/WsConsumerLoopFull.java:unsubscribe_data_code_piece}} ``` @@ -644,7 +644,7 @@ Rust 连接器创建消费者的参数为 DSN, 可以设置的参数列表请 {{#include docs/examples/rust/restexample/examples/tmq.rs:unsubscribe}} ``` -**注意**:消费者取消订阅后无法重用,如果想订阅新的 `topic`, 请重新创建消费者。 +**注意**:消费者取消订阅后已经关闭,无法重用,如果想订阅新的 `topic`, 请重新创建消费者。 @@ -672,7 +672,7 @@ Rust 连接器创建消费者的参数为 DSN, 可以设置的参数列表请 ```java -{{#include examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WsConsumerLoopFull.java:unsubscribe_data_code_piece}} +{{#include docs/examples/java/src/main/java/com/taos/example/WsConsumerLoopFull.java:unsubscribe_data_code_piece}} ``` @@ -694,7 +694,7 @@ Rust 连接器创建消费者的参数为 DSN, 可以设置的参数列表请 {{#include docs/examples/rust/restexample/examples/tmq.rs:unsubscribe}} ``` -**注意**:消费者取消订阅后无法重用,如果想订阅新的 `topic`, 请重新创建消费者。 +**注意**:消费者取消订阅后已经关闭,无法重用,如果想订阅新的 `topic`, 请重新创建消费者。 不支持 @@ -723,7 +723,7 @@ Rust 连接器创建消费者的参数为 DSN, 可以设置的参数列表请
完整代码示例 ```java -{{#include examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WsConsumerLoopFull.java:consumer_demo}} +{{#include docs/examples/java/src/main/java/com/taos/example/WsConsumerLoopFull.java:consumer_demo}} ``` **注意**:这里的 value.deserializer 配置参数值应该根据测试环境的包路径做相应的调整。 @@ -788,7 +788,7 @@ Rust 连接器创建消费者的参数为 DSN, 可以设置的参数列表请
完整代码示例 ```java -{{#include examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ConsumerLoopFull.java:consumer_demo}} +{{#include docs/examples/java/src/main/java/com/taos/example/ConsumerLoopFull.java:consumer_demo}} ``` **注意**:这里的 value.deserializer 配置参数值应该根据测试环境的包路径做相应的调整。 diff --git a/docs/zh/14-reference/05-connector/14-java.mdx b/docs/zh/14-reference/05-connector/14-java.mdx index 0dc85feb13..f355aea621 100644 --- a/docs/zh/14-reference/05-connector/14-java.mdx +++ b/docs/zh/14-reference/05-connector/14-java.mdx @@ -60,7 +60,7 @@ REST 连接支持所有能运行 Java 的平台。 在报错后,通过 SQLException 可以获取到错误的信息和错误码: ```java -{{#include examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcBasicDemo.java:jdbc_exception}} +{{#include docs/examples/java/src/main/java/com/taos/example/JdbcBasicDemo.java:jdbc_exception}} ``` JDBC 连接器可能报错的错误码包括 4 种: diff --git a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ConsumerLoopFull.java b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ConsumerLoopFull.java index 34629fb8d2..ce9af5ecdc 100644 --- a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ConsumerLoopFull.java +++ b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ConsumerLoopFull.java @@ -20,7 +20,7 @@ public class ConsumerLoopFull { static private Statement statement; static private volatile boolean stopThread = false; - public static TaosConsumer getConsumer() throws SQLException { + public static TaosConsumer getConsumer() throws Exception { // ANCHOR: create_consumer Properties config = new Properties(); config.setProperty("td.connect.type", "jni"); @@ -38,16 +38,20 @@ public class ConsumerLoopFull { try { TaosConsumer consumer= new TaosConsumer<>(config); - System.out.println("Create consumer successfully, host: " + config.getProperty("bootstrap.servers") + ", groupId: " + config.getProperty("group.id") + ", clientId: " + config.getProperty("client.id")); + System.out.printf("Create consumer successfully, host: %s, groupId: %s, clientId: %s%n", + config.getProperty("bootstrap.servers"), + config.getProperty("group.id"), + config.getProperty("client.id")); return consumer; - } catch (SQLException ex) { - // handle any errors, please refer to the JDBC specifications for detailed exceptions info - System.out.println("Failed to create native consumer, host: " + config.getProperty("bootstrap.servers") + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to create consumer", ex); } catch (Exception ex) { - System.out.println("Failed to create native consumer, host: " + config.getProperty("bootstrap.servers") - + "; ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to create consumer", ex); + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to create native consumer, host: %s, %sErrMessage: %s%n", + config.getProperty("bootstrap.servers"), + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; } // ANCHOR_END: create_consumer } @@ -69,14 +73,14 @@ public class ConsumerLoopFull { System.out.println("data: " + JSON.toJSONString(bean)); } } - - } catch (SQLException ex) { - // handle any errors, please refer to the JDBC specifications for detailed exceptions info - System.out.println("Failed to poll data, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to poll data", ex); } catch (Exception ex) { - System.out.println("Failed to poll data, ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to poll data", ex); + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to poll data, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; } // ANCHOR_END: poll_data_code_piece } @@ -100,13 +104,14 @@ public class ConsumerLoopFull { consumer.seekToBeginning(assignment); System.out.println("Assignment seek to beginning successfully."); - } catch (SQLException ex) { - // handle any errors, please refer to the JDBC specifications for detailed exceptions info - System.out.println("Seek example failed; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw new SQLException("seek example failed", ex); } catch (Exception ex) { - System.out.println("Seek example failed; ErrMessage: " + ex.getMessage()); - throw new SQLException("seek example failed", ex); + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to execute seek example, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; } // ANCHOR_END: consumer_seek } @@ -131,13 +136,14 @@ public class ConsumerLoopFull { System.out.println("Commit offset manually successfully."); } } - } catch (SQLException ex) { - // handle any errors, please refer to the JDBC specifications for detailed exceptions info - System.out.println("Failed to execute consumer functions. ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to execute consumer functions", ex); } catch (Exception ex) { - System.out.println("Failed to execute consumer functions. ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to execute consumer functions", ex); + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to execute commit example, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; } // ANCHOR_END: commit_code_piece } @@ -150,13 +156,14 @@ public class ConsumerLoopFull { // unsubscribe the consumer consumer.unsubscribe(); System.out.println("Consumer unsubscribed successfully."); - } catch (SQLException ex) { - // handle any errors, please refer to the JDBC specifications for detailed exceptions info - System.out.println("Failed to unsubscribe consumer. ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to unsubscribe consumer", ex); } catch (Exception ex) { - System.out.println("Failed to unsubscribe consumer. ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to unsubscribe consumer", ex); + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to unsubscribe consumer, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; } finally { // close the consumer @@ -238,9 +245,14 @@ public class ConsumerLoopFull { i++; Thread.sleep(1); } - } catch (SQLException ex) { - System.out.println("Failed to insert data to power.meters, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to insert data to power.meters", ex); + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to insert data to power.meters, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; } } @@ -250,9 +262,14 @@ public class ConsumerLoopFull { statement.executeUpdate("USE power"); statement.executeUpdate("CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))"); statement.executeUpdate("CREATE TOPIC IF NOT EXISTS topic_meters AS SELECT ts, current, voltage, phase, groupid, location FROM meters"); - } catch (SQLException ex) { - System.out.println("Failed to create db and table, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to create db and table", ex); + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to create db and table, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; } } @@ -311,7 +328,7 @@ public class ConsumerLoopFull { try { prepareData(); } catch (SQLException ex) { - System.out.println("Failed to prepare data, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); + System.out.println("Failed to prepare data, ErrCode:" + ex.getErrorCode() + ", ErrMessage: " + ex.getMessage()); return; } catch (Exception ex) { System.out.println("Failed to prepare data, ErrMessage: " + ex.getMessage()); diff --git a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcCreatDBDemo.java b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcCreatDBDemo.java index ca50c4ca77..28d7d2d67b 100644 --- a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcCreatDBDemo.java +++ b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcCreatDBDemo.java @@ -35,13 +35,13 @@ public class JdbcCreatDBDemo { rowsAffected = stmt.executeUpdate("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))"); // you can check rowsAffected here System.out.println("Create stable power.meters successfully, rowsAffected: " + rowsAffected); - - } catch (SQLException ex) { - // handle any errors, please refer to the JDBC specifications for detailed exceptions info - System.out.println("Failed to create db and table, url:" + jdbcUrl + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw ex; - } catch (Exception ex){ - System.out.println("Failed to create db and table, url:" + jdbcUrl + "; ErrMessage: " + ex.getMessage()); + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to create database power or stable meters, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); throw ex; } // ANCHOR_END: create_db_and_table diff --git a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcInsertDataDemo.java b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcInsertDataDemo.java index 7e60c10bf7..08798b755c 100644 --- a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcInsertDataDemo.java +++ b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcInsertDataDemo.java @@ -40,12 +40,13 @@ public class JdbcInsertDataDemo { int affectedRows = stmt.executeUpdate(insertQuery); // you can check affectedRows here System.out.println("Successfully inserted " + affectedRows + " rows to power.meters."); - } catch (SQLException ex) { - // handle any errors, please refer to the JDBC specifications for detailed exceptions info - System.out.println("Failed to insert data to power.meters, url:" + jdbcUrl + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw ex; - } catch (Exception ex){ - System.out.println("Failed to insert data to power.meters, url:" + jdbcUrl + "; ErrMessage: " + ex.getMessage()); + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to insert data to power.meters, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); throw ex; } // ANCHOR_END: insert_data diff --git a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcQueryDemo.java b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcQueryDemo.java index ea6d8346c6..768ba8929c 100644 --- a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcQueryDemo.java +++ b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcQueryDemo.java @@ -24,10 +24,11 @@ public class JdbcQueryDemo { properties.setProperty("timezone", "UTC-8"); System.out.println("get connection starting..."); // ANCHOR: query_data + String sql = "SELECT ts, current, location FROM power.meters limit 100"; try (Connection connection = DriverManager.getConnection(jdbcUrl, properties); Statement stmt = connection.createStatement(); // query data, make sure the database and table are created before - ResultSet resultSet = stmt.executeQuery("SELECT ts, current, location FROM power.meters limit 100")) { + ResultSet resultSet = stmt.executeQuery(sql)) { Timestamp ts; float current; @@ -41,19 +42,16 @@ public class JdbcQueryDemo { // you can check data here System.out.printf("ts: %s, current: %f, location: %s %n", ts, current, location); } - } catch (SQLException ex) { - // handle any errors, please refer to the JDBC specifications for detailed exceptions info - System.out.println("Failed to query data from power.meters, url:" + jdbcUrl + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw ex; - } catch (Exception ex){ - System.out.println("Failed to query data from power.meters, url:" + jdbcUrl + "; ErrMessage: " + ex.getMessage()); + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to query data from power.meters, sql: %s, %sErrMessage: %s%n", + sql, + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); throw ex; } // ANCHOR_END: query_data } - - private static void printResult(ResultSet resultSet) throws SQLException { - Util.printResult(resultSet); - } - } diff --git a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcReqIdDemo.java b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcReqIdDemo.java index 7dd99c58dc..dd4b549bc5 100644 --- a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcReqIdDemo.java +++ b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcReqIdDemo.java @@ -45,12 +45,13 @@ public class JdbcReqIdDemo { } } - } catch (SQLException ex) { - // handle any errors, please refer to the JDBC specifications for detailed exceptions info - System.out.println("Failed to execute sql with reqId: " + reqId + ", url:" + jdbcUrl + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw ex; - } catch (Exception ex){ - System.out.println("Failed to execute sql with reqId: " + reqId + ", url:" + jdbcUrl + "; ErrMessage: " + ex.getMessage()); + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to execute sql with reqId: %s, %sErrMessage: %s%n", reqId, + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); throw ex; } // ANCHOR_END: with_reqid diff --git a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ParameterBindingBasicDemo.java b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ParameterBindingBasicDemo.java index ab93e324ea..b5732f0e33 100644 --- a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ParameterBindingBasicDemo.java +++ b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ParameterBindingBasicDemo.java @@ -68,12 +68,13 @@ public class ParameterBindingBasicDemo { // you can check exeResult here System.out.println("Successfully inserted " + (numOfSubTable * numOfRow) + " rows to power.meters."); } - } catch (SQLException ex) { - // handle any errors, please refer to the JDBC specifications for detailed exceptions info - System.out.println("Failed to insert to table meters using stmt, url: " + jdbcUrl + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw ex; - } catch (Exception ex){ - System.out.println("Failed to insert to table meters using stmt, url: " + jdbcUrl + "; ErrMessage: " + ex.getMessage()); + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to insert to table meters using stmt, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); throw ex; } } diff --git a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/SchemalessJniTest.java b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/SchemalessJniTest.java index d1f6eb3cea..5b1ce51be6 100644 --- a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/SchemalessJniTest.java +++ b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/SchemalessJniTest.java @@ -26,12 +26,13 @@ public class SchemalessJniTest { conn.write(telnetDemo, SchemalessProtocolType.TELNET, SchemalessTimestampType.MILLI_SECONDS); conn.write(jsonDemo, SchemalessProtocolType.JSON, SchemalessTimestampType.NOT_CONFIGURED); System.out.println("Inserted data with schemaless successfully."); - } catch (SQLException ex) { - // handle any errors, please refer to the JDBC specifications for detailed exceptions info - System.out.println("Failed to insert data with schemaless, host:" + host + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw ex; - } catch (Exception ex){ - System.out.println("Failed to insert data with schemaless, host:" + host + "; ErrMessage: " + ex.getMessage()); + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to insert data with schemaless, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); throw ex; } } diff --git a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/SchemalessWsTest.java b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/SchemalessWsTest.java index 6432c8100e..0f15e70224 100644 --- a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/SchemalessWsTest.java +++ b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/SchemalessWsTest.java @@ -26,12 +26,13 @@ public class SchemalessWsTest { conn.write(telnetDemo, SchemalessProtocolType.TELNET, SchemalessTimestampType.MILLI_SECONDS); conn.write(jsonDemo, SchemalessProtocolType.JSON, SchemalessTimestampType.SECONDS); System.out.println("Inserted data with schemaless successfully."); - } catch (SQLException ex) { - // handle any errors, please refer to the JDBC specifications for detailed exceptions info - System.out.println("Failed to insert data with schemaless, host:" + host + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw ex; - } catch (Exception ex){ - System.out.println("Failed to insert data with schemaless, host:" + host + "; ErrMessage: " + ex.getMessage()); + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to insert data with schemaless, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); throw ex; } } diff --git a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WSParameterBindingBasicDemo.java b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WSParameterBindingBasicDemo.java index 29013014b9..792ee4ed2d 100644 --- a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WSParameterBindingBasicDemo.java +++ b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WSParameterBindingBasicDemo.java @@ -47,12 +47,13 @@ public class WSParameterBindingBasicDemo { System.out.println("Successfully inserted " + exeResult.length + " rows to power.meters."); } } - } catch (SQLException ex) { - // handle any errors, please refer to the JDBC specifications for detailed exceptions info - System.out.println("Failed to insert to table meters using stmt, url: " + jdbcUrl + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw ex; - } catch (Exception ex){ - System.out.println("Failed to insert to table meters using stmt, url: " + jdbcUrl + "; ErrMessage: " + ex.getMessage()); + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to insert to table meters using stmt, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); throw ex; } } diff --git a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WsConsumerLoopFull.java b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WsConsumerLoopFull.java index 241ab2df76..17380023cd 100644 --- a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WsConsumerLoopFull.java +++ b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WsConsumerLoopFull.java @@ -6,11 +6,13 @@ import com.taosdata.jdbc.tmq.*; import java.sql.*; import java.time.Duration; -import java.util.*; +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -import java.util.function.Consumer; // ANCHOR: consumer_demo public class WsConsumerLoopFull { @@ -18,7 +20,7 @@ public class WsConsumerLoopFull { static private Statement statement; static private volatile boolean stopThread = false; - public static TaosConsumer getConsumer() throws SQLException { + public static TaosConsumer getConsumer() throws Exception { // ANCHOR: create_consumer Properties config = new Properties(); config.setProperty("td.connect.type", "ws"); @@ -36,16 +38,20 @@ public class WsConsumerLoopFull { try { TaosConsumer consumer= new TaosConsumer<>(config); - System.out.println("Create consumer successfully, host: " + config.getProperty("bootstrap.servers") + ", groupId: " + config.getProperty("group.id") + ", clientId: " + config.getProperty("client.id")); + System.out.printf("Create consumer successfully, host: %s, groupId: %s, clientId: %s%n", + config.getProperty("bootstrap.servers"), + config.getProperty("group.id"), + config.getProperty("client.id")); return consumer; - } catch (SQLException ex) { - // handle any errors, please refer to the JDBC specifications for detailed exceptions info - System.out.println("Failed to create websocket consumer, host: " + config.getProperty("bootstrap.servers") + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to create consumer", ex); } catch (Exception ex) { - System.out.println("Failed to create websocket consumer, host: " + config.getProperty("bootstrap.servers") - + "; ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to create consumer", ex); + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to create websocket consumer, host: %s, %sErrMessage: %s%n", + config.getProperty("bootstrap.servers"), + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; } // ANCHOR_END: create_consumer } @@ -67,14 +73,14 @@ public class WsConsumerLoopFull { System.out.println("data: " + JSON.toJSONString(bean)); } } - - } catch (SQLException ex) { - // handle any errors, please refer to the JDBC specifications for detailed exceptions info - System.out.println("Failed to poll data, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to poll data", ex); } catch (Exception ex) { - System.out.println("Failed to poll data, ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to poll data", ex); + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to poll data, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; } // ANCHOR_END: poll_data_code_piece } @@ -98,13 +104,14 @@ public class WsConsumerLoopFull { consumer.seekToBeginning(assignment); System.out.println("Assignment seek to beginning successfully."); - } catch (SQLException ex) { - // handle any errors, please refer to the JDBC specifications for detailed exceptions info - System.out.println("Seek example failed; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw new SQLException("seek example failed", ex); } catch (Exception ex) { - System.out.println("Seek example failed; ErrMessage: " + ex.getMessage()); - throw new SQLException("seek example failed", ex); + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to execute seek example, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; } // ANCHOR_END: consumer_seek } @@ -129,13 +136,14 @@ public class WsConsumerLoopFull { System.out.println("Commit offset manually successfully."); } } - } catch (SQLException ex) { - // handle any errors, please refer to the JDBC specifications for detailed exceptions info - System.out.println("Failed to execute consumer functions. ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to execute consumer functions", ex); } catch (Exception ex) { - System.out.println("Failed to execute consumer functions. ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to execute consumer functions", ex); + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to execute commit example, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; } // ANCHOR_END: commit_code_piece } @@ -148,13 +156,14 @@ public class WsConsumerLoopFull { // unsubscribe the consumer consumer.unsubscribe(); System.out.println("Consumer unsubscribed successfully."); - } catch (SQLException ex) { - // handle any errors, please refer to the JDBC specifications for detailed exceptions info - System.out.println("Failed to unsubscribe consumer. ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to unsubscribe consumer", ex); } catch (Exception ex) { - System.out.println("Failed to unsubscribe consumer. ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to unsubscribe consumer", ex); + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to unsubscribe consumer, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; } finally { // close the consumer @@ -236,9 +245,14 @@ public class WsConsumerLoopFull { i++; Thread.sleep(1); } - } catch (SQLException ex) { - System.out.println("Failed to insert data to power.meters, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to insert data to power.meters", ex); + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to insert data to power.meters, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; } } @@ -248,9 +262,14 @@ public class WsConsumerLoopFull { statement.executeUpdate("USE power"); statement.executeUpdate("CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))"); statement.executeUpdate("CREATE TOPIC IF NOT EXISTS topic_meters AS SELECT ts, current, voltage, phase, groupid, location FROM meters"); - } catch (SQLException ex) { - System.out.println("Failed to create db and table, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to create db and table", ex); + } catch (Exception ex) { + // please refer to the JDBC specifications for detailed exceptions info + System.out.printf("Failed to create db and table, %sErrMessage: %s%n", + ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", + ex.getMessage()); + // Print stack trace for context in examples. Use logging in production. + ex.printStackTrace(); + throw ex; } } @@ -309,7 +328,7 @@ public class WsConsumerLoopFull { try { prepareData(); } catch (SQLException ex) { - System.out.println("Failed to prepare data, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); + System.out.println("Failed to prepare data, ErrCode:" + ex.getErrorCode() + ", ErrMessage: " + ex.getMessage()); return; } catch (Exception ex) { System.out.println("Failed to prepare data, ErrMessage: " + ex.getMessage()); @@ -334,8 +353,7 @@ public class WsConsumerLoopFull { consumer.unsubscribe(); unsubscribeExample(consumer); - System.out.println("unsubscribeExample executed successfully."); - + System.out.println("unsubscribeExample executed successfully"); } catch (SQLException ex) { System.out.println("Failed to poll data from topic_meters, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); return; diff --git a/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/DruidDemo.java b/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/DruidDemo.java index dd96f5c632..a366efd419 100644 --- a/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/DruidDemo.java +++ b/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/DruidDemo.java @@ -2,35 +2,35 @@ package com.taosdata.example; import com.alibaba.druid.pool.DruidDataSource; -import javax.sql.DataSource; import java.sql.Connection; import java.sql.Statement; public class DruidDemo { -// ANCHOR: connection_pool -public static void main(String[] args) throws Exception { - String url = "jdbc:TAOS://127.0.0.1:6030/log"; + // ANCHOR: connection_pool + public static void main(String[] args) throws Exception { + String url = "jdbc:TAOS://127.0.0.1:6030/log"; - DruidDataSource dataSource = new DruidDataSource(); - // jdbc properties - dataSource.setDriverClassName("com.taosdata.jdbc.TSDBDriver"); - dataSource.setUrl(url); - dataSource.setUsername("root"); - dataSource.setPassword("taosdata"); - // pool configurations - dataSource.setInitialSize(10); - dataSource.setMinIdle(10); - dataSource.setMaxActive(10); - dataSource.setMaxWait(30000); - dataSource.setValidationQuery("SELECT SERVER_VERSION()"); + DruidDataSource dataSource = new DruidDataSource(); + // jdbc properties + dataSource.setDriverClassName("com.taosdata.jdbc.TSDBDriver"); + dataSource.setUrl(url); + dataSource.setUsername("root"); + dataSource.setPassword("taosdata"); + // pool configurations + dataSource.setInitialSize(10); + dataSource.setMinIdle(10); + dataSource.setMaxActive(10); + dataSource.setMaxWait(30000); + dataSource.setValidationQuery("SELECT SERVER_VERSION()"); - Connection connection = dataSource.getConnection(); // get connection - Statement statement = connection.createStatement(); // get statement - //query or insert - // ... + Connection connection = dataSource.getConnection(); // get connection + Statement statement = connection.createStatement(); // get statement + // query or insert + // ... - statement.close(); - connection.close(); // put back to connection pool -} -// ANCHOR_END: connection_pool + statement.close(); + connection.close(); // put back to connection pool + dataSource.close(); + } + // ANCHOR_END: connection_pool } diff --git a/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/HikariDemo.java b/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/HikariDemo.java index 4480cbc7c4..50b20fdb0c 100644 --- a/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/HikariDemo.java +++ b/examples/JDBC/connectionPools/src/main/java/com/taosdata/example/HikariDemo.java @@ -4,34 +4,34 @@ import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import java.sql.Connection; -import java.sql.SQLException; import java.sql.Statement; public class HikariDemo { -// ANCHOR: connection_pool -public static void main(String[] args) throws SQLException { - HikariConfig config = new HikariConfig(); - // jdbc properties - config.setJdbcUrl("jdbc:TAOS://127.0.0.1:6030/log"); - config.setUsername("root"); - config.setPassword("taosdata"); - // connection pool configurations - config.setMinimumIdle(10); //minimum number of idle connection - config.setMaximumPoolSize(10); //maximum number of connection in the pool - config.setConnectionTimeout(30000); //maximum wait milliseconds for get connection from pool - config.setMaxLifetime(0); // maximum life time for each connection - config.setIdleTimeout(0); // max idle time for recycle idle connection - config.setConnectionTestQuery("SELECT SERVER_VERSION()"); //validation query + // ANCHOR: connection_pool + public static void main(String[] args) throws Exception { + HikariConfig config = new HikariConfig(); + // jdbc properties + config.setJdbcUrl("jdbc:TAOS://127.0.0.1:6030/log"); + config.setUsername("root"); + config.setPassword("taosdata"); + // connection pool configurations + config.setMinimumIdle(10); // minimum number of idle connection + config.setMaximumPoolSize(10); // maximum number of connection in the pool + config.setConnectionTimeout(30000); // maximum wait milliseconds for get connection from pool + config.setMaxLifetime(0); // maximum life time for each connection + config.setIdleTimeout(0); // max idle time for recycle idle connection + config.setConnectionTestQuery("SELECT SERVER_VERSION()"); // validation query - HikariDataSource ds = new HikariDataSource(config); //create datasource + HikariDataSource dataSource = new HikariDataSource(config); // create datasource - Connection connection = ds.getConnection(); // get connection - Statement statement = connection.createStatement(); // get statement + Connection connection = dataSource.getConnection(); // get connection + Statement statement = connection.createStatement(); // get statement - //query or insert - // ... - statement.close(); - connection.close(); // put back to connection pool -} -// ANCHOR_END: connection_pool + // query or insert + // ... + statement.close(); + connection.close(); // put back to connection pool + dataSource.close(); + } + // ANCHOR_END: connection_pool } From 8aa9fb82d3ad851f1e6507a1458738f594fafe28 Mon Sep 17 00:00:00 2001 From: sheyanjie-qq <249478495@qq.com> Date: Wed, 14 Aug 2024 16:40:19 +0800 Subject: [PATCH 03/22] update c sample code --- docs/examples/c/create_db_demo.c | 6 +- docs/examples/c/insert_data_demo.c | 86 ++++++------- docs/examples/c/query_data_demo.c | 95 +++++++------- docs/examples/c/sml_insert_demo.c | 197 +++++++++++++++-------------- docs/examples/c/tmq_demo.c | 79 ++++++------ docs/examples/c/with_reqid_demo.c | 98 +++++++------- 6 files changed, 282 insertions(+), 279 deletions(-) diff --git a/docs/examples/c/create_db_demo.c b/docs/examples/c/create_db_demo.c index 45d4a17c5c..7ac54041d8 100644 --- a/docs/examples/c/create_db_demo.c +++ b/docs/examples/c/create_db_demo.c @@ -43,8 +43,7 @@ static int DemoCreateDB() { TAOS_RES *result = taos_query(taos, "CREATE DATABASE IF NOT EXISTS power"); code = taos_errno(result); if (code != 0) { - printf("Failed to create database power, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, code, - taos_errstr(result)); + printf("Failed to create database power, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(result)); taos_close(taos); taos_cleanup(); return -1; @@ -59,8 +58,7 @@ static int DemoCreateDB() { result = taos_query(taos, sql); code = taos_errno(result); if (code != 0) { - printf("Failed to create stable power.meters, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s\n.", host, port, code, - taos_errstr(result)); + printf("Failed to create stable power.meters, ErrCode: 0x%x, ErrMessage: %s\n.", code, taos_errstr(result)); taos_close(taos); taos_cleanup(); return -1; diff --git a/docs/examples/c/insert_data_demo.c b/docs/examples/c/insert_data_demo.c index 3d655edca3..edc6b0b750 100644 --- a/docs/examples/c/insert_data_demo.c +++ b/docs/examples/c/insert_data_demo.c @@ -23,52 +23,52 @@ #include "taos.h" static int DemoInsertData() { -// ANCHOR: insert_data -const char *host = "localhost"; -const char *user = "root"; -const char *password = "taosdata"; -uint16_t port = 6030; -int code = 0; + // ANCHOR: insert_data + const char *host = "localhost"; + const char *user = "root"; + const char *password = "taosdata"; + uint16_t port = 6030; + int code = 0; -// connect -TAOS *taos = taos_connect(host, user, password, NULL, port); -if (taos == NULL) { - printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL)); - taos_cleanup(); - return -1; -} + // connect + TAOS *taos = taos_connect(host, user, password, NULL, port); + if (taos == NULL) { + printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), + taos_errstr(NULL)); + taos_cleanup(); + return -1; + } -// insert data, please make sure the database and table are already created -const char* sql = "INSERT INTO " \ - "power.d1001 USING power.meters TAGS(2,'California.SanFrancisco') " \ - "VALUES " \ - "(NOW + 1a, 10.30000, 219, 0.31000) " \ - "(NOW + 2a, 12.60000, 218, 0.33000) " \ - "(NOW + 3a, 12.30000, 221, 0.31000) " \ - "power.d1002 USING power.meters TAGS(3, 'California.SanFrancisco') " \ - "VALUES " \ - "(NOW + 1a, 10.30000, 218, 0.25000) "; -TAOS_RES *result = taos_query(taos, sql); -code = taos_errno(result); -if (code != 0) { - printf("Failed to insert data to power.meters, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s\n.", host, port, code, taos_errstr(result)); + // insert data, please make sure the database and table are already created + const char *sql = + "INSERT INTO " + "power.d1001 USING power.meters TAGS(2,'California.SanFrancisco') " + "VALUES " + "(NOW + 1a, 10.30000, 219, 0.31000) " + "(NOW + 2a, 12.60000, 218, 0.33000) " + "(NOW + 3a, 12.30000, 221, 0.31000) " + "power.d1002 USING power.meters TAGS(3, 'California.SanFrancisco') " + "VALUES " + "(NOW + 1a, 10.30000, 218, 0.25000) "; + TAOS_RES *result = taos_query(taos, sql); + code = taos_errno(result); + if (code != 0) { + printf("Failed to insert data to power.meters, ErrCode: 0x%x, ErrMessage: %s\n.", code, taos_errstr(result)); + taos_close(taos); + taos_cleanup(); + return -1; + } + taos_free_result(result); + + // you can check affectedRows here + int rows = taos_affected_rows(result); + printf("Successfully inserted %d rows into power.meters.\n", rows); + + // close & clean taos_close(taos); taos_cleanup(); - return -1; -} -taos_free_result(result); - -// you can check affectedRows here -int rows = taos_affected_rows(result); -printf("Successfully inserted %d rows into power.meters.\n", rows); - -// close & clean -taos_close(taos); -taos_cleanup(); -return 0; -// ANCHOR_END: insert_data + return 0; + // ANCHOR_END: insert_data } -int main(int argc, char *argv[]) { - return DemoInsertData(); -} +int main(int argc, char *argv[]) { return DemoInsertData(); } diff --git a/docs/examples/c/query_data_demo.c b/docs/examples/c/query_data_demo.c index e58c467ccf..f2c6662d9e 100644 --- a/docs/examples/c/query_data_demo.c +++ b/docs/examples/c/query_data_demo.c @@ -22,61 +22,58 @@ #include #include "taos.h" - static int DemoQueryData() { -// ANCHOR: query_data -const char *host = "localhost"; -const char *user = "root"; -const char *password = "taosdata"; -uint16_t port = 6030; -int code = 0; + // ANCHOR: query_data + const char *host = "localhost"; + const char *user = "root"; + const char *password = "taosdata"; + uint16_t port = 6030; + int code = 0; -// connect -TAOS *taos = taos_connect(host, user, password, NULL, port); -if (taos == NULL) { - printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL)); - taos_cleanup(); - return -1; -} + // connect + TAOS *taos = taos_connect(host, user, password, NULL, port); + if (taos == NULL) { + printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), + taos_errstr(NULL)); + taos_cleanup(); + return -1; + } + // query data, please make sure the database and table are already created + const char *sql = "SELECT ts, current, location FROM power.meters limit 100"; + TAOS_RES *result = taos_query(taos, sql); + code = taos_errno(result); + if (code != 0) { + printf("Failed to query data from power.meters, sql: %s, ErrCode: 0x%x, ErrMessage: %s\n.", sql, code, + taos_errstr(result)); + taos_close(taos); + taos_cleanup(); + return -1; + } + TAOS_ROW row = NULL; + int rows = 0; + int num_fields = taos_field_count(result); + TAOS_FIELD *fields = taos_fetch_fields(result); -// query data, please make sure the database and table are already created -const char* sql = "SELECT ts, current, location FROM power.meters limit 100"; -TAOS_RES *result = taos_query(taos, sql); -code = taos_errno(result); -if (code != 0) { - printf("Failed to query data from power.meters, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s\n.", host, port, code, taos_errstr(result)); + printf("fields: %d\n", num_fields); + printf("sql: %s, result:\n", sql); + + // fetch the records row by row + while ((row = taos_fetch_row(result))) { + char temp[1024] = {0}; + rows++; + taos_print_row(temp, row, fields, num_fields); + printf("%s\n", temp); + } + printf("total rows: %d\n", rows); + taos_free_result(result); + + // close & clean taos_close(taos); taos_cleanup(); - return -1; + return 0; + // ANCHOR_END: query_data } -TAOS_ROW row = NULL; -int rows = 0; -int num_fields = taos_field_count(result); -TAOS_FIELD *fields = taos_fetch_fields(result); - -printf("fields: %d\n", num_fields); -printf("sql: %s, result:\n", sql); - -// fetch the records row by row -while ((row = taos_fetch_row(result))) { - char temp[1024] = {0}; - rows++; - taos_print_row(temp, row, fields, num_fields); - printf("%s\n", temp); -} -printf("total rows: %d\n", rows); -taos_free_result(result); - -// close & clean -taos_close(taos); -taos_cleanup(); -return 0; -// ANCHOR_END: query_data -} - -int main(int argc, char *argv[]) { - return DemoQueryData(); -} +int main(int argc, char *argv[]) { return DemoQueryData(); } diff --git a/docs/examples/c/sml_insert_demo.c b/docs/examples/c/sml_insert_demo.c index 807fd10501..1107734c78 100644 --- a/docs/examples/c/sml_insert_demo.c +++ b/docs/examples/c/sml_insert_demo.c @@ -21,114 +21,119 @@ #include #include "taos.h" - static int DemoSmlInsert() { -// ANCHOR: schemaless -const char *host = "localhost"; -const char *user = "root"; -const char *password = "taosdata"; -uint16_t port = 6030; -int code = 0; + // ANCHOR: schemaless + const char *host = "localhost"; + const char *user = "root"; + const char *password = "taosdata"; + uint16_t port = 6030; + int code = 0; -// connect -TAOS *taos = taos_connect(host, user, password, NULL, port); -if (taos == NULL) { - printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL)); - taos_cleanup(); - return -1; -} + // connect + TAOS *taos = taos_connect(host, user, password, NULL, port); + if (taos == NULL) { + printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), + taos_errstr(NULL)); + taos_cleanup(); + return -1; + } -// create database -TAOS_RES *result = taos_query(taos, "CREATE DATABASE IF NOT EXISTS power"); -code = taos_errno(result); -if (code != 0) { - printf("Failed to create database power, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, code, taos_errstr(result)); - taos_close(taos); - taos_cleanup(); - return -1; -} -taos_free_result(result); -printf("Create database power successfully.\n"); + // create database + TAOS_RES *result = taos_query(taos, "CREATE DATABASE IF NOT EXISTS power"); + code = taos_errno(result); + if (code != 0) { + printf("Failed to create database power, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(result)); + taos_close(taos); + taos_cleanup(); + return -1; + } + taos_free_result(result); + printf("Create database power successfully.\n"); -// use database -result = taos_query(taos, "USE power"); -code = taos_errno(result); -if (code != 0) { - printf("Failed to execute use power, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s\n.", host, port, code, taos_errstr(result)); - taos_close(taos); - taos_cleanup(); - return -1; -} -taos_free_result(result); + // use database + result = taos_query(taos, "USE power"); + code = taos_errno(result); + if (code != 0) { + printf("Failed to execute use power, ErrCode: 0x%x, ErrMessage: %s\n.", code, taos_errstr(result)); + taos_close(taos); + taos_cleanup(); + return -1; + } + taos_free_result(result); -// schemaless demo data -char * line_demo = "meters,groupid=2,location=California.SanFrancisco current=10.3000002f64,voltage=219i32,phase=0.31f64 1626006833639"; -char * telnet_demo = "metric_telnet 1707095283260 4 host=host0 interface=eth0"; -char * json_demo = "{\"metric\": \"metric_json\",\"timestamp\": 1626846400,\"value\": 10.3, \"tags\": {\"groupid\": 2, \"location\": \"California.SanFrancisco\", \"id\": \"d1001\"}}"; + // schemaless demo data + char *line_demo = + "meters,groupid=2,location=California.SanFrancisco current=10.3000002f64,voltage=219i32,phase=0.31f64 " + "1626006833639"; + char *telnet_demo = "metric_telnet 1707095283260 4 host=host0 interface=eth0"; + char *json_demo = + "{\"metric\": \"metric_json\",\"timestamp\": 1626846400,\"value\": 10.3, \"tags\": {\"groupid\": 2, " + "\"location\": \"California.SanFrancisco\", \"id\": \"d1001\"}}"; -// influxdb line protocol -char *lines[] = {line_demo}; -result = taos_schemaless_insert(taos, lines, 1, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_MILLI_SECONDS); -code = taos_errno(result); -if (code != 0) { - printf("Failed to insert schemaless line data, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s\n.", host, port, code, taos_errstr(result)); - taos_close(taos); - taos_cleanup(); - return -1; -} + // influxdb line protocol + char *lines[] = {line_demo}; + result = taos_schemaless_insert(taos, lines, 1, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_MILLI_SECONDS); + code = taos_errno(result); + if (code != 0) { + printf("Failed to insert schemaless line data, data: %s, ErrCode: 0x%x, ErrMessage: %s\n.", line_demo, code, + taos_errstr(result)); + taos_close(taos); + taos_cleanup(); + return -1; + } -int rows = taos_affected_rows(result); -printf("Insert %d rows of schemaless line data successfully.\n", rows); -taos_free_result(result); + int rows = taos_affected_rows(result); + printf("Insert %d rows of schemaless line data successfully.\n", rows); + taos_free_result(result); -// opentsdb telnet protocol -char *telnets[] = {telnet_demo}; -result = taos_schemaless_insert(taos, telnets, 1, TSDB_SML_TELNET_PROTOCOL, TSDB_SML_TIMESTAMP_MILLI_SECONDS); -code = taos_errno(result); -if (code != 0) { - printf("Failed to insert schemaless telnet data, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s\n.", host, port, code, taos_errstr(result)); - taos_close(taos); - taos_cleanup(); - return -1; -} + // opentsdb telnet protocol + char *telnets[] = {telnet_demo}; + result = taos_schemaless_insert(taos, telnets, 1, TSDB_SML_TELNET_PROTOCOL, TSDB_SML_TIMESTAMP_MILLI_SECONDS); + code = taos_errno(result); + if (code != 0) { + printf("Failed to insert schemaless telnet data, data: %s, ErrCode: 0x%x, ErrMessage: %s\n.", telnet_demo, code, + taos_errstr(result)); + taos_close(taos); + taos_cleanup(); + return -1; + } -rows = taos_affected_rows(result); -printf("Insert %d rows of schemaless telnet data successfully.\n", rows); -taos_free_result(result); + rows = taos_affected_rows(result); + printf("Insert %d rows of schemaless telnet data successfully.\n", rows); + taos_free_result(result); -// opentsdb json protocol -char *jsons[1] = {0}; -// allocate memory for json data. can not use static memory. -jsons[0] = malloc(1024); -if (jsons[0] == NULL) { - printf("Failed to allocate memory\n"); - taos_close(taos); - taos_cleanup(); - return -1; -} -(void)strncpy(jsons[0], json_demo, 1023); -result = taos_schemaless_insert(taos, jsons, 1, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); -code = taos_errno(result); -if (code != 0) { + // opentsdb json protocol + char *jsons[1] = {0}; + // allocate memory for json data. can not use static memory. + jsons[0] = malloc(1024); + if (jsons[0] == NULL) { + printf("Failed to allocate memory\n"); + taos_close(taos); + taos_cleanup(); + return -1; + } + (void)strncpy(jsons[0], json_demo, 1023); + result = taos_schemaless_insert(taos, jsons, 1, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + code = taos_errno(result); + if (code != 0) { + free(jsons[0]); + printf("Failed to insert schemaless json data, Server: %s, ErrCode: 0x%x, ErrMessage: %s\n.", json_demo, code, + taos_errstr(result)); + taos_close(taos); + taos_cleanup(); + return -1; + } free(jsons[0]); - printf("Failed to insert schemaless json data, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s\n.", host, port, code, taos_errstr(result)); + + rows = taos_affected_rows(result); + printf("Insert %d rows of schemaless json data successfully.\n", rows); + taos_free_result(result); + + // close & clean taos_close(taos); taos_cleanup(); - return -1; -} -free(jsons[0]); - -rows = taos_affected_rows(result); -printf("Insert %d rows of schemaless json data successfully.\n", rows); -taos_free_result(result); - -// close & clean -taos_close(taos); -taos_cleanup(); -return 0; -// ANCHOR_END: schemaless + return 0; + // ANCHOR_END: schemaless } -int main(int argc, char *argv[]) { - return DemoSmlInsert(); -} +int main(int argc, char *argv[]) { return DemoSmlInsert(); } diff --git a/docs/examples/c/tmq_demo.c b/docs/examples/c/tmq_demo.c index e7a2425c7d..55ec568dc5 100644 --- a/docs/examples/c/tmq_demo.c +++ b/docs/examples/c/tmq_demo.c @@ -41,14 +41,15 @@ typedef struct { } ConsumerConfig; void* prepare_data(void* arg) { - const char *host = "localhost"; - const char *user = "root"; - const char *password = "taosdata"; - uint16_t port = 6030; - int code = 0; - TAOS *pConn = taos_connect(host, user, password, NULL, port); + const char* host = "localhost"; + const char* user = "root"; + const char* password = "taosdata"; + uint16_t port = 6030; + int code = 0; + TAOS* pConn = taos_connect(host, user, password, NULL, port); if (pConn == NULL) { - fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL)); + fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), + taos_errstr(NULL)); taos_cleanup(); return NULL; } @@ -68,7 +69,8 @@ void* prepare_data(void* arg) { pRes = taos_query(pConn, buf); code = taos_errno(pRes); if (code != 0) { - fprintf(stderr, "Failed to insert data to power.meters, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes)); + fprintf(stderr, "Failed to insert data to power.meters, ErrCode: 0x%x, ErrMessage: %s.\n", code, + taos_errstr(pRes)); } taos_free_result(pRes); sleep(1); @@ -115,14 +117,15 @@ static int32_t msg_process(TAOS_RES* msg) { // ANCHOR_END: msg_process static int32_t init_env() { - const char *host = "localhost"; - const char *user = "root"; - const char *password = "taosdata"; - uint16_t port = 6030; - int code = 0; - TAOS *pConn = taos_connect(host, user, password, NULL, port); + const char* host = "localhost"; + const char* user = "root"; + const char* password = "taosdata"; + uint16_t port = 6030; + int code = 0; + TAOS* pConn = taos_connect(host, user, password, NULL, port); if (pConn == NULL) { - fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL)); + fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), + taos_errstr(NULL)); taos_cleanup(); return -1; } @@ -177,15 +180,16 @@ END: int32_t create_topic() { fprintf(stdout, "Create topic.\n"); - TAOS_RES* pRes; - const char *host = "localhost"; - const char *user = "root"; - const char *password = "taosdata"; - uint16_t port = 6030; - int code = 0; - TAOS *pConn = taos_connect(host, user, password, NULL, port); + TAOS_RES* pRes; + const char* host = "localhost"; + const char* user = "root"; + const char* password = "taosdata"; + uint16_t port = 6030; + int code = 0; + TAOS* pConn = taos_connect(host, user, password, NULL, port); if (pConn == NULL) { - fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL)); + fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), + taos_errstr(NULL)); taos_cleanup(); return -1; } @@ -348,7 +352,8 @@ void consume_repeatly(tmq_t* tmq) { code = tmq_offset_seek(tmq, topic_name, p->vgId, p->begin); if (code != 0) { - fprintf(stderr, "Failed to seek assignment %d to beginning %ld, ErrCode: 0x%x, ErrMessage: %s.\n", i, p->begin, code, tmq_err2str(code)); + fprintf(stderr, "Failed to seek assignment %d to beginning %ld, ErrCode: 0x%x, ErrMessage: %s.\n", i, p->begin, + code, tmq_err2str(code)); } else { fprintf(stdout, "Seek assignment %d to beginning %ld successfully.\n", i, p->begin); } @@ -417,25 +422,25 @@ int main(int argc, char* argv[]) { return -1; } - ConsumerConfig config = { - .enable_auto_commit = "true", - .auto_commit_interval_ms = "1000", - .group_id = "group1", - .client_id = "client1", - .td_connect_host = "localhost", - .td_connect_port = "6030", - .td_connect_user = "root", - .td_connect_pass = "taosdata", - .auto_offset_reset = "latest" - }; + ConsumerConfig config = {.enable_auto_commit = "true", + .auto_commit_interval_ms = "1000", + .group_id = "group1", + .client_id = "client1", + .td_connect_host = "localhost", + .td_connect_port = "6030", + .td_connect_user = "root", + .td_connect_pass = "taosdata", + .auto_offset_reset = "latest"}; // ANCHOR: create_consumer_2 tmq_t* tmq = build_consumer(&config); if (NULL == tmq) { - fprintf(stderr, "Failed to create native consumer, host: %s, groupId: %s, , clientId: %s.\n", config.td_connect_host, config.group_id, config.client_id); + fprintf(stderr, "Failed to create native consumer, host: %s, groupId: %s, , clientId: %s.\n", + config.td_connect_host, config.group_id, config.client_id); return -1; } else { - fprintf(stdout, "Create consumer successfully, host: %s, groupId: %s, , clientId: %s.\n", config.td_connect_host, config.group_id, config.client_id); + fprintf(stdout, "Create consumer successfully, host: %s, groupId: %s, , clientId: %s.\n", config.td_connect_host, + config.group_id, config.client_id); } // ANCHOR_END: create_consumer_2 diff --git a/docs/examples/c/with_reqid_demo.c b/docs/examples/c/with_reqid_demo.c index 724b682850..b3e4e79e39 100644 --- a/docs/examples/c/with_reqid_demo.c +++ b/docs/examples/c/with_reqid_demo.c @@ -23,59 +23,57 @@ #include "taos.h" static int DemoWithReqId() { -// ANCHOR: with_reqid -const char *host = "localhost"; -const char *user = "root"; -const char *password = "taosdata"; -uint16_t port = 6030; -int code = 0; + // ANCHOR: with_reqid + const char *host = "localhost"; + const char *user = "root"; + const char *password = "taosdata"; + uint16_t port = 6030; + int code = 0; -// connect -TAOS *taos = taos_connect(host, user, password, NULL, port); -if (taos == NULL) { - printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL)); - taos_cleanup(); - return -1; -} + // connect + TAOS *taos = taos_connect(host, user, password, NULL, port); + if (taos == NULL) { + printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), + taos_errstr(NULL)); + taos_cleanup(); + return -1; + } -const char *sql = "SELECT ts, current, location FROM power.meters limit 1"; -// query data with reqid -long reqid = 3L; -TAOS_RES *result = taos_query_with_reqid(taos, sql, reqid); -code = taos_errno(result); -if (code != 0) { - printf("Failed to execute sql with reqId: %ld, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s\n.", reqid, host, port, code, taos_errstr(result)); + const char *sql = "SELECT ts, current, location FROM power.meters limit 1"; + // query data with reqid + long reqid = 3L; + TAOS_RES *result = taos_query_with_reqid(taos, sql, reqid); + code = taos_errno(result); + if (code != 0) { + printf("Failed to execute sql with reqId: %ld, ErrCode: 0x%x, ErrMessage: %s\n.", reqid, code, taos_errstr(result)); + taos_close(taos); + taos_cleanup(); + return -1; + } + + TAOS_ROW row = NULL; + int rows = 0; + int num_fields = taos_field_count(result); + TAOS_FIELD *fields = taos_fetch_fields(result); + + printf("fields: %d\n", num_fields); + printf("sql: %s, result:\n", sql); + + // fetch the records row by row + while ((row = taos_fetch_row(result))) { + char temp[1024] = {0}; + rows++; + taos_print_row(temp, row, fields, num_fields); + printf("%s\n", temp); + } + printf("total rows: %d\n", rows); + taos_free_result(result); + + // close & clean taos_close(taos); taos_cleanup(); - return -1; -} - -TAOS_ROW row = NULL; -int rows = 0; -int num_fields = taos_field_count(result); -TAOS_FIELD *fields = taos_fetch_fields(result); - -printf("fields: %d\n", num_fields); -printf("sql: %s, result:\n", sql); - -// fetch the records row by row -while ((row = taos_fetch_row(result))) { - char temp[1024] = {0}; - rows++; - taos_print_row(temp, row, fields, num_fields); - printf("%s\n", temp); -} -printf("total rows: %d\n", rows); -taos_free_result(result); - -// close & clean -taos_close(taos); -taos_cleanup(); -return 0; -// ANCHOR_END: with_reqid -} - -int main(int argc, char *argv[]) { - return DemoWithReqId(); + return 0; + // ANCHOR_END: with_reqid } +int main(int argc, char *argv[]) { return DemoWithReqId(); } From d99e6be4c1934f6365228c26042a5c2ce9bbbeae Mon Sep 17 00:00:00 2001 From: Yaming Pei Date: Wed, 14 Aug 2024 18:08:07 +0800 Subject: [PATCH 04/22] mod c sample code --- docs/examples/c/create_db_demo.c | 4 +++- docs/examples/c/insert_data_demo.c | 4 +++- docs/examples/c/query_data_demo.c | 11 ++++++++--- docs/examples/c/sml_insert_demo.c | 5 +++-- docs/examples/c/tmq_demo.c | 4 ---- docs/examples/c/with_reqid_demo.c | 11 ++++++++--- 6 files changed, 25 insertions(+), 14 deletions(-) diff --git a/docs/examples/c/create_db_demo.c b/docs/examples/c/create_db_demo.c index 7ac54041d8..44960defa5 100644 --- a/docs/examples/c/create_db_demo.c +++ b/docs/examples/c/create_db_demo.c @@ -73,4 +73,6 @@ static int DemoCreateDB() { // ANCHOR_END: create_db_and_table } -int main(int argc, char *argv[]) { return DemoCreateDB(); } +int main(int argc, char *argv[]) { + return DemoCreateDB(); +} diff --git a/docs/examples/c/insert_data_demo.c b/docs/examples/c/insert_data_demo.c index edc6b0b750..e880af0cd6 100644 --- a/docs/examples/c/insert_data_demo.c +++ b/docs/examples/c/insert_data_demo.c @@ -71,4 +71,6 @@ static int DemoInsertData() { // ANCHOR_END: insert_data } -int main(int argc, char *argv[]) { return DemoInsertData(); } +int main(int argc, char *argv[]) { + return DemoInsertData(); +} diff --git a/docs/examples/c/query_data_demo.c b/docs/examples/c/query_data_demo.c index f2c6662d9e..097a6b99b8 100644 --- a/docs/examples/c/query_data_demo.c +++ b/docs/examples/c/query_data_demo.c @@ -62,9 +62,12 @@ static int DemoQueryData() { // fetch the records row by row while ((row = taos_fetch_row(result))) { char temp[1024] = {0}; - rows++; - taos_print_row(temp, row, fields, num_fields); + if (taos_print_row(temp, row, fields, num_fields) < 0) { + printf("Failed to print row\n"); + break; + } printf("%s\n", temp); + rows++; } printf("total rows: %d\n", rows); taos_free_result(result); @@ -76,4 +79,6 @@ static int DemoQueryData() { // ANCHOR_END: query_data } -int main(int argc, char *argv[]) { return DemoQueryData(); } +int main(int argc, char *argv[]) { + return DemoQueryData(); +} diff --git a/docs/examples/c/sml_insert_demo.c b/docs/examples/c/sml_insert_demo.c index 1107734c78..9adbb28f87 100644 --- a/docs/examples/c/sml_insert_demo.c +++ b/docs/examples/c/sml_insert_demo.c @@ -48,7 +48,6 @@ static int DemoSmlInsert() { return -1; } taos_free_result(result); - printf("Create database power successfully.\n"); // use database result = taos_query(taos, "USE power"); @@ -136,4 +135,6 @@ static int DemoSmlInsert() { // ANCHOR_END: schemaless } -int main(int argc, char *argv[]) { return DemoSmlInsert(); } +int main(int argc, char *argv[]) { + return DemoSmlInsert(); +} diff --git a/docs/examples/c/tmq_demo.c b/docs/examples/c/tmq_demo.c index 55ec568dc5..e8e28e1df4 100644 --- a/docs/examples/c/tmq_demo.c +++ b/docs/examples/c/tmq_demo.c @@ -132,7 +132,6 @@ static int32_t init_env() { TAOS_RES* pRes; // drop database if exists - fprintf(stdout, "Create database.\n"); pRes = taos_query(pConn, "DROP TOPIC IF EXISTS topic_meters"); code = taos_errno(pRes); if (code != 0) { @@ -157,7 +156,6 @@ static int32_t init_env() { taos_free_result(pRes); // create super table - fprintf(stdout, "Create super table.\n"); pRes = taos_query( pConn, "CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS " @@ -179,7 +177,6 @@ END: } int32_t create_topic() { - fprintf(stdout, "Create topic.\n"); TAOS_RES* pRes; const char* host = "localhost"; const char* user = "root"; @@ -382,7 +379,6 @@ void manual_commit(tmq_t* tmq) { totalRows += msg_process(tmqmsg); // commit the message int32_t code = tmq_commit_sync(tmq, tmqmsg); - if (code) { fprintf(stderr, "Failed to commit message, ErrCode: 0x%x, ErrMessage: %s.\n", code, tmq_err2str(code)); // free the message diff --git a/docs/examples/c/with_reqid_demo.c b/docs/examples/c/with_reqid_demo.c index b3e4e79e39..c6e87686e9 100644 --- a/docs/examples/c/with_reqid_demo.c +++ b/docs/examples/c/with_reqid_demo.c @@ -62,9 +62,12 @@ static int DemoWithReqId() { // fetch the records row by row while ((row = taos_fetch_row(result))) { char temp[1024] = {0}; - rows++; - taos_print_row(temp, row, fields, num_fields); + if (taos_print_row(temp, row, fields, num_fields) < 0) { + printf("Failed to print row\n"); + break; + } printf("%s\n", temp); + rows++; } printf("total rows: %d\n", rows); taos_free_result(result); @@ -76,4 +79,6 @@ static int DemoWithReqId() { // ANCHOR_END: with_reqid } -int main(int argc, char *argv[]) { return DemoWithReqId(); } +int main(int argc, char *argv[]) { + return DemoWithReqId(); +} From e599f68480fe0da2766d6d4964ea40632dd11fa8 Mon Sep 17 00:00:00 2001 From: sheyanjie-qq <249478495@qq.com> Date: Wed, 14 Aug 2024 19:46:39 +0800 Subject: [PATCH 05/22] fix link error --- docs/zh/08-develop/01-connect/index.md | 2 +- docs/zh/26-tdinternal/03-storage.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/zh/08-develop/01-connect/index.md b/docs/zh/08-develop/01-connect/index.md index 280e31b2a6..092a50869a 100644 --- a/docs/zh/08-develop/01-connect/index.md +++ b/docs/zh/08-develop/01-connect/index.md @@ -99,7 +99,7 @@ TDengine 提供了丰富的应用程序开发接口,为了便于用户快速 - **安装前准备** - 安装 Python。新近版本 taospy 包要求 Python 3.6.2+。早期版本 taospy 包要求 Python 3.7+。taos-ws-py 包要求 Python 3.7+。如果系统上还没有 Python 可参考 [Python BeginnersGuide](https://wiki.python.org/moin/BeginnersGuide/Download) 安装。 - 安装 [pip](https://pypi.org/project/pip/)。大部分情况下 Python 的安装包都自带了 pip 工具, 如果没有请参考 [pip documentation](https://pip.pypa.io/en/stable/installation/) 安装。 - - 如果使用原生连接,还需[安装客户端驱动](../#安装客户端驱动)。客户端软件包含了 TDengine 客户端动态链接库(libtaos.so 或 taos.dll) 和 TDengine CLI。 + - 如果使用原生连接,还需[安装客户端驱动](../connect/#安装客户端驱动-taosc)。客户端软件包含了 TDengine 客户端动态链接库(libtaos.so 或 taos.dll) 和 TDengine CLI。 - **使用 pip 安装** - 卸载旧版本 diff --git a/docs/zh/26-tdinternal/03-storage.md b/docs/zh/26-tdinternal/03-storage.md index f65f06e85b..e402babdd7 100644 --- a/docs/zh/26-tdinternal/03-storage.md +++ b/docs/zh/26-tdinternal/03-storage.md @@ -101,7 +101,7 @@ head 文件是时序数据存储文件(data 文件)的 BRIN(Block Range In head 文件中存储了多个 BRIN 记录块及其索引。BRIN 记录块采用列存压缩的方式,这种方式可以大大减少空间占用,同时保持较高的查询性能。BRIN 索引结构如下图所示: -![BRIN 索引结构](./brin.png) +![BRIN 索引结构](./brin.png) #### data 文件 @@ -121,4 +121,4 @@ data 文件是实际存储时序数据的文件。在 data 文件中,时序数 在少表高频的场景下,系统仅维护一个 stt 文件。该文件专门用于存储每次数据落盘后剩余的碎片数据。这样,在下一次数据落盘时,这些碎片数据可以与内存中的新数据合并,形成较大的数据块,随后一并写入 data 文件中。这种机制有效地避免了数据文件的碎片化,确保了数据存储的连续性和高效性。 -对于多表低频的场景,建议配置多个 stt 文件。这种场景下的核心思想是,尽管单张表每次落盘的数据量可能不大,但同一超级表下的所有子表累积的数据量却相当可观。通过合并这些数据,可以生成较大的数据块,从而减少数据块的碎片化。这不仅提升了数据的写入效率,还能显著提高查询性能,因为连续的数据存储更有利于快速的数据检索和访问。 \ No newline at end of file +对于多表低频的场景,建议配置多个 stt 文件。这种场景下的核心思想是,尽管单张表每次落盘的数据量可能不大,但同一超级表下的所有子表累积的数据量却相当可观。通过合并这些数据,可以生成较大的数据块,从而减少数据块的碎片化。这不仅提升了数据的写入效率,还能显著提高查询性能,因为连续的数据存储更有利于快速的数据检索和访问。 From 81eca8fadb64c1b4539d56adcda00f45b6811aee Mon Sep 17 00:00:00 2001 From: t_max <1172915550@qq.com> Date: Thu, 15 Aug 2024 10:01:13 +0800 Subject: [PATCH 06/22] docs: the download address uses absolute url --- docs/zh/04-get-started/03-package.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/zh/04-get-started/03-package.md b/docs/zh/04-get-started/03-package.md index 4906a2fcfa..7df41af831 100644 --- a/docs/zh/04-get-started/03-package.md +++ b/docs/zh/04-get-started/03-package.md @@ -146,7 +146,7 @@ Note: 从 3.0.1.7 开始,只提供 TDengine 客户端的 Windows 客户端的 :::info -下载其他组件、最新 Beta 版及之前版本的安装包,请点击[发布历史页面](../../releases/tdengine)。 +下载其他组件、最新 Beta 版及之前版本的安装包,请点击[发布历史页面](https://docs.taosdata.com/releases/tdengine/)。 ::: :::note From f4c1ad0fdea1e5f6340c754733df6743f5318d6b Mon Sep 17 00:00:00 2001 From: menshibin Date: Thu, 15 Aug 2024 13:06:47 +0800 Subject: [PATCH 07/22] modify exec error --- docs/examples/python/schemaless_ws.py | 13 +++++++------ docs/examples/python/stmt_native.py | 4 ++-- docs/examples/python/stmt_ws.py | 4 ++-- docs/examples/python/tmq_native.py | 2 +- 4 files changed, 12 insertions(+), 11 deletions(-) diff --git a/docs/examples/python/schemaless_ws.py b/docs/examples/python/schemaless_ws.py index 3c41d1768b..39de55393d 100644 --- a/docs/examples/python/schemaless_ws.py +++ b/docs/examples/python/schemaless_ws.py @@ -1,19 +1,21 @@ import taosws +host = "localhost" +port = 6041 def prepare(): conn = None try: conn = taosws.connect(user="root", password="taosdata", - host="localhost", - port=6041) + host=host, + port=port) # create database rowsAffected = conn.execute(f"CREATE DATABASE IF NOT EXISTS power") assert rowsAffected == 0 except Exception as err: - print(f"Failed to create db and table, err:{err}") + print(f"Failed to create db and table, db addrr:{host}:{port} ; ErrMessage:{err}") raise err finally: if conn: @@ -32,8 +34,7 @@ def schemaless_insert(): jsonDemo = [ '{"metric": "metric_json","timestamp": 1626846400,"value": 10.3, "tags": {"groupid": 2, "location": "California.SanFrancisco", "id": "d1001"}}' ] - host = "localhost" - port = 6041 + try: conn = taosws.connect(user="root", password="taosdata", @@ -76,6 +77,6 @@ def schemaless_insert(): if __name__ == "__main__": try: prepare() - schemaless_insert + schemaless_insert() except Exception as err: print(f"Failed to insert data with schemaless, err:{err}") diff --git a/docs/examples/python/stmt_native.py b/docs/examples/python/stmt_native.py index 16975d6895..a1af7d1dd7 100644 --- a/docs/examples/python/stmt_native.py +++ b/docs/examples/python/stmt_native.py @@ -7,8 +7,8 @@ numOfRow = 10 conn = None stmt = None -host="localhost", -port=6030, +host="localhost" +port=6030 try: conn = taos.connect( user="root", diff --git a/docs/examples/python/stmt_ws.py b/docs/examples/python/stmt_ws.py index 74f071fde1..45d9222315 100644 --- a/docs/examples/python/stmt_ws.py +++ b/docs/examples/python/stmt_ws.py @@ -13,8 +13,8 @@ port=6041 try: conn = taosws.connect(user="root", password="taosdata", - host="localhost", - port=6041) + host=host, + port=port) conn.execute("CREATE DATABASE IF NOT EXISTS power") conn.execute("USE power") diff --git a/docs/examples/python/tmq_native.py b/docs/examples/python/tmq_native.py index 8181e1c2db..22a9b805bc 100644 --- a/docs/examples/python/tmq_native.py +++ b/docs/examples/python/tmq_native.py @@ -50,7 +50,7 @@ from taos.tmq import Consumer def create_consumer(): host = "localhost" - port = 6030 + port = "6030" groupId = "group1" clientId = "1" try: From d9dbf95c5eca2585bfabb1c8a3ded577bdcac9ec Mon Sep 17 00:00:00 2001 From: menshibin Date: Thu, 15 Aug 2024 13:37:06 +0800 Subject: [PATCH 08/22] modify exec error --- docs/examples/node/websocketexample/tmq_example.js | 4 ++-- docs/examples/node/websocketexample/tmq_seek_example.js | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/examples/node/websocketexample/tmq_example.js b/docs/examples/node/websocketexample/tmq_example.js index b0e52360c9..fc9d2889e0 100644 --- a/docs/examples/node/websocketexample/tmq_example.js +++ b/docs/examples/node/websocketexample/tmq_example.js @@ -62,7 +62,7 @@ async function subscribe(consumer) { for (let [key, value] of res) { console.log(`data: ${key} ${value}`); } - consumer.commit(); + await consumer.commit(); console.log("Commit offset manually successfully."); } } catch (err) { @@ -77,7 +77,7 @@ async function test() { let consumer = null; try { await prepare(); - let consumer = await createConsumer() + consumer = await createConsumer() await subscribe(consumer) await consumer.unsubscribe(); console.log("Consumer unsubscribed successfully."); diff --git a/docs/examples/node/websocketexample/tmq_seek_example.js b/docs/examples/node/websocketexample/tmq_seek_example.js index 0dea7e1671..259614d5db 100644 --- a/docs/examples/node/websocketexample/tmq_seek_example.js +++ b/docs/examples/node/websocketexample/tmq_seek_example.js @@ -31,7 +31,7 @@ async function prepare() { conf.setUser('root'); conf.setPwd('taosdata'); conf.setDb('power'); - const createDB = `CREATE DATABASE IF NOT EXISTS POWER ${db} KEEP 3650 DURATION 10 BUFFER 16 WAL_LEVEL 1;`; + const createDB = `CREATE DATABASE IF NOT EXISTS ${db} KEEP 3650 DURATION 10 BUFFER 16 WAL_LEVEL 1;`; const createStable = `CREATE STABLE IF NOT EXISTS ${db}.${stable} (ts timestamp, current float, voltage int, phase float) TAGS (location binary(64), groupId int);`; let wsSql = await taos.sqlConnect(conf); @@ -45,7 +45,7 @@ async function prepare() { for (let i = 0; i < 10; i++) { await wsSql.exec(`INSERT INTO d1001 USING ${stable} (location, groupId) TAGS ("California.SanFrancisco", 3) VALUES (NOW, ${10 + i}, ${200 + i}, ${0.32 + i})`); } - wsSql.Close(); + await wsSql.close(); } // ANCHOR: subscribe From 9a0f7aeedb97ad33352a2d54d033b2d3dd226944 Mon Sep 17 00:00:00 2001 From: sheyanjie-qq <249478495@qq.com> Date: Thu, 15 Aug 2024 14:28:35 +0800 Subject: [PATCH 09/22] mod rest api desc --- docs/zh/08-develop/01-connect/index.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/zh/08-develop/01-connect/index.md b/docs/zh/08-develop/01-connect/index.md index 092a50869a..d1aeb0ed8b 100644 --- a/docs/zh/08-develop/01-connect/index.md +++ b/docs/zh/08-develop/01-connect/index.md @@ -399,7 +399,8 @@ C/C++ 语言连接器使用 `taos_connect()` 函数用于建立与 TDengine 数 -使用 REST API 方式访问 TDengine,由应用程序去建立 HTTP 连接,自己控制 HTTP 连接参数。 +通过 REST API 方式访问 TDengine 时,应用程序直接与 taosAdapter 建立 HTTP 连接,建议使用连接池来管理连接。 +使用 REST API 的参数具体可以参考:[http-请求格式](../../reference/connector/rest-api/#http-请求格式) From 3d9380b51a5da3cfc598cb38cb5c6207f6d4ba9d Mon Sep 17 00:00:00 2001 From: sheyanjie-qq <249478495@qq.com> Date: Fri, 16 Aug 2024 11:28:03 +0800 Subject: [PATCH 10/22] update java sample code --- .../com/taos/example/ConsumerLoopFull.java | 43 +- .../com/taos/example/JdbcInsertDataDemo.java | 23 +- .../com/taos/example/WsConsumerLoopFull.java | 41 +- .../taosdata/example/ConsumerLoopFull.java | 384 ------------------ .../com/taosdata/example/JdbcCreatDBDemo.java | 55 --- .../taosdata/example/JdbcInsertDataDemo.java | 54 --- .../com/taosdata/example/JdbcQueryDemo.java | 57 --- .../com/taosdata/example/JdbcReqIdDemo.java | 64 --- .../example/ParameterBindingBasicDemo.java | 90 ---- .../taosdata/example/SchemalessJniTest.java | 47 --- .../taosdata/example/SchemalessWsTest.java | 47 --- .../example/WSParameterBindingBasicDemo.java | 69 ---- .../taosdata/example/WsConsumerLoopFull.java | 384 ------------------ 13 files changed, 67 insertions(+), 1291 deletions(-) delete mode 100644 examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ConsumerLoopFull.java delete mode 100644 examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcCreatDBDemo.java delete mode 100644 examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcInsertDataDemo.java delete mode 100644 examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcQueryDemo.java delete mode 100644 examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcReqIdDemo.java delete mode 100644 examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ParameterBindingBasicDemo.java delete mode 100644 examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/SchemalessJniTest.java delete mode 100644 examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/SchemalessWsTest.java delete mode 100644 examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WSParameterBindingBasicDemo.java delete mode 100644 examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WsConsumerLoopFull.java diff --git a/docs/examples/java/src/main/java/com/taos/example/ConsumerLoopFull.java b/docs/examples/java/src/main/java/com/taos/example/ConsumerLoopFull.java index 62dac019d7..ec9faf383e 100644 --- a/docs/examples/java/src/main/java/com/taos/example/ConsumerLoopFull.java +++ b/docs/examples/java/src/main/java/com/taos/example/ConsumerLoopFull.java @@ -19,8 +19,10 @@ public class ConsumerLoopFull { static private Connection connection; static private Statement statement; static private volatile boolean stopThread = false; + static private String groupId = "group1"; + static private String clientId = "clinet1"; - public static TaosConsumer getConsumer() throws Exception { + public static TaosConsumer getConsumer() throws Exception { // ANCHOR: create_consumer Properties config = new Properties(); config.setProperty("td.connect.type", "jni"); @@ -30,7 +32,7 @@ public class ConsumerLoopFull { config.setProperty("enable.auto.commit", "true"); config.setProperty("auto.commit.interval.ms", "1000"); config.setProperty("group.id", "group1"); - config.setProperty("client.id", "1"); + config.setProperty("client.id", "clinet1"); config.setProperty("td.connect.user", "root"); config.setProperty("td.connect.pass", "taosdata"); config.setProperty("value.deserializer", "com.taos.example.ConsumerLoopFull$ResultDeserializer"); @@ -45,8 +47,10 @@ public class ConsumerLoopFull { return consumer; } catch (Exception ex) { // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to create native consumer, host: %s, %sErrMessage: %s%n", + System.out.printf("Failed to create websocket consumer, host: %s, groupId: %s, clientId: %s, %sErrMessage: %s%n", config.getProperty("bootstrap.servers"), + config.getProperty("group.id"), + config.getProperty("client.id"), ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", ex.getMessage()); // Print stack trace for context in examples. Use logging in production. @@ -58,9 +62,8 @@ public class ConsumerLoopFull { public static void pollExample(TaosConsumer consumer) throws SQLException { // ANCHOR: poll_data_code_piece + List topics = Collections.singletonList("topic_meters"); try { - List topics = Collections.singletonList("topic_meters"); - // subscribe to the topics consumer.subscribe(topics); System.out.println("Subscribe topics successfully."); @@ -69,13 +72,16 @@ public class ConsumerLoopFull { ConsumerRecords records = consumer.poll(Duration.ofMillis(100)); for (ConsumerRecord record : records) { ResultBean bean = record.value(); - // process the data here + // Add your data processing logic here System.out.println("data: " + JSON.toJSONString(bean)); } } } catch (Exception ex) { // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to poll data, %sErrMessage: %s%n", + System.out.printf("Failed to poll data, topic: %s, groupId: %s, clientId: %s, %sErrMessage: %s%n", + topics.get(0), + groupId, + clientId, ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", ex.getMessage()); // Print stack trace for context in examples. Use logging in production. @@ -87,9 +93,8 @@ public class ConsumerLoopFull { public static void seekExample(TaosConsumer consumer) throws SQLException { // ANCHOR: consumer_seek + List topics = Collections.singletonList("topic_meters"); try { - List topics = Collections.singletonList("topic_meters"); - // subscribe to the topics consumer.subscribe(topics); System.out.println("Subscribe topics successfully."); @@ -106,7 +111,10 @@ public class ConsumerLoopFull { System.out.println("Assignment seek to beginning successfully."); } catch (Exception ex) { // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to execute seek example, %sErrMessage: %s%n", + System.out.printf("Failed to seek offset, topic: %s, groupId: %s, clientId: %s, %sErrMessage: %s%n", + topics.get(0), + groupId, + clientId, ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", ex.getMessage()); // Print stack trace for context in examples. Use logging in production. @@ -119,15 +127,14 @@ public class ConsumerLoopFull { public static void commitExample(TaosConsumer consumer) throws SQLException { // ANCHOR: commit_code_piece + List topics = Collections.singletonList("topic_meters"); try { - List topics = Collections.singletonList("topic_meters"); - consumer.subscribe(topics); for (int i = 0; i < 50; i++) { ConsumerRecords records = consumer.poll(Duration.ofMillis(100)); for (ConsumerRecord record : records) { ResultBean bean = record.value(); - // process your data here + // Add your data processing logic here System.out.println("data: " + JSON.toJSONString(bean)); } if (!records.isEmpty()) { @@ -138,7 +145,10 @@ public class ConsumerLoopFull { } } catch (Exception ex) { // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to execute commit example, %sErrMessage: %s%n", + System.out.printf("Failed to commit offset, topic: %s, groupId: %s, clientId: %s, %sErrMessage: %s%n", + topics.get(0), + groupId, + clientId, ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", ex.getMessage()); // Print stack trace for context in examples. Use logging in production. @@ -158,7 +168,10 @@ public class ConsumerLoopFull { System.out.println("Consumer unsubscribed successfully."); } catch (Exception ex) { // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to unsubscribe consumer, %sErrMessage: %s%n", + System.out.printf("Failed to unsubscribe consumer, topic: %s, groupId: %s, clientId: %s, %sErrMessage: %s%n", + topics.get(0), + groupId, + clientId, ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", ex.getMessage()); // Print stack trace for context in examples. Use logging in production. diff --git a/docs/examples/java/src/main/java/com/taos/example/JdbcInsertDataDemo.java b/docs/examples/java/src/main/java/com/taos/example/JdbcInsertDataDemo.java index f19017193c..5c3599d819 100644 --- a/docs/examples/java/src/main/java/com/taos/example/JdbcInsertDataDemo.java +++ b/docs/examples/java/src/main/java/com/taos/example/JdbcInsertDataDemo.java @@ -25,25 +25,26 @@ public class JdbcInsertDataDemo { properties.setProperty("timezone", "UTC-8"); System.out.println("get connection starting..."); // ANCHOR: insert_data + // insert data, please make sure the database and table are created before + String insertQuery = "INSERT INTO " + + "power.d1001 USING power.meters TAGS(2,'California.SanFrancisco') " + + "VALUES " + + "(NOW + 1a, 10.30000, 219, 0.31000) " + + "(NOW + 2a, 12.60000, 218, 0.33000) " + + "(NOW + 3a, 12.30000, 221, 0.31000) " + + "power.d1002 USING power.meters TAGS(3, 'California.SanFrancisco') " + + "VALUES " + + "(NOW + 1a, 10.30000, 218, 0.25000) "; try (Connection connection = DriverManager.getConnection(jdbcUrl, properties); Statement stmt = connection.createStatement()) { - // insert data, please make sure the database and table are created before - String insertQuery = "INSERT INTO " + - "power.d1001 USING power.meters TAGS(2,'California.SanFrancisco') " + - "VALUES " + - "(NOW + 1a, 10.30000, 219, 0.31000) " + - "(NOW + 2a, 12.60000, 218, 0.33000) " + - "(NOW + 3a, 12.30000, 221, 0.31000) " + - "power.d1002 USING power.meters TAGS(3, 'California.SanFrancisco') " + - "VALUES " + - "(NOW + 1a, 10.30000, 218, 0.25000) "; int affectedRows = stmt.executeUpdate(insertQuery); // you can check affectedRows here System.out.println("Successfully inserted " + affectedRows + " rows to power.meters."); } catch (Exception ex) { // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to insert data to power.meters, %sErrMessage: %s%n", + System.out.printf("Failed to insert data to power.meters, sql: %s, %sErrMessage: %s%n", + insertQuery, ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", ex.getMessage()); // Print stack trace for context in examples. Use logging in production. diff --git a/docs/examples/java/src/main/java/com/taos/example/WsConsumerLoopFull.java b/docs/examples/java/src/main/java/com/taos/example/WsConsumerLoopFull.java index 66c37f172e..6db65f47f2 100644 --- a/docs/examples/java/src/main/java/com/taos/example/WsConsumerLoopFull.java +++ b/docs/examples/java/src/main/java/com/taos/example/WsConsumerLoopFull.java @@ -19,6 +19,8 @@ public class WsConsumerLoopFull { static private Connection connection; static private Statement statement; static private volatile boolean stopThread = false; + static private String groupId = "group1"; + static private String clientId = "clinet1"; public static TaosConsumer getConsumer() throws Exception { // ANCHOR: create_consumer @@ -30,7 +32,7 @@ public class WsConsumerLoopFull { config.setProperty("enable.auto.commit", "true"); config.setProperty("auto.commit.interval.ms", "1000"); config.setProperty("group.id", "group1"); - config.setProperty("client.id", "1"); + config.setProperty("client.id", "clinet1"); config.setProperty("td.connect.user", "root"); config.setProperty("td.connect.pass", "taosdata"); config.setProperty("value.deserializer", "com.taos.example.WsConsumerLoopFull$ResultDeserializer"); @@ -45,8 +47,10 @@ public class WsConsumerLoopFull { return consumer; } catch (Exception ex) { // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to create websocket consumer, host: %s, %sErrMessage: %s%n", + System.out.printf("Failed to create websocket consumer, host: %s, groupId: %s, clientId: %s, %sErrMessage: %s%n", config.getProperty("bootstrap.servers"), + config.getProperty("group.id"), + config.getProperty("client.id"), ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", ex.getMessage()); // Print stack trace for context in examples. Use logging in production. @@ -58,9 +62,8 @@ public class WsConsumerLoopFull { public static void pollExample(TaosConsumer consumer) throws SQLException { // ANCHOR: poll_data_code_piece + List topics = Collections.singletonList("topic_meters"); try { - List topics = Collections.singletonList("topic_meters"); - // subscribe to the topics consumer.subscribe(topics); System.out.println("Subscribe topics successfully."); @@ -69,13 +72,16 @@ public class WsConsumerLoopFull { ConsumerRecords records = consumer.poll(Duration.ofMillis(100)); for (ConsumerRecord record : records) { ResultBean bean = record.value(); - // process the data here + // Add your data processing logic here System.out.println("data: " + JSON.toJSONString(bean)); } } } catch (Exception ex) { // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to poll data, %sErrMessage: %s%n", + System.out.printf("Failed to poll data, topic: %s, groupId: %s, clientId: %s, %sErrMessage: %s%n", + topics.get(0), + groupId, + clientId, ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", ex.getMessage()); // Print stack trace for context in examples. Use logging in production. @@ -87,9 +93,8 @@ public class WsConsumerLoopFull { public static void seekExample(TaosConsumer consumer) throws SQLException { // ANCHOR: consumer_seek + List topics = Collections.singletonList("topic_meters"); try { - List topics = Collections.singletonList("topic_meters"); - // subscribe to the topics consumer.subscribe(topics); System.out.println("Subscribe topics successfully."); @@ -106,7 +111,10 @@ public class WsConsumerLoopFull { System.out.println("Assignment seek to beginning successfully."); } catch (Exception ex) { // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to execute seek example, %sErrMessage: %s%n", + System.out.printf("Failed to seek offset, topic: %s, groupId: %s, clientId: %s, %sErrMessage: %s%n", + topics.get(0), + groupId, + clientId, ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", ex.getMessage()); // Print stack trace for context in examples. Use logging in production. @@ -119,15 +127,14 @@ public class WsConsumerLoopFull { public static void commitExample(TaosConsumer consumer) throws SQLException { // ANCHOR: commit_code_piece + List topics = Collections.singletonList("topic_meters"); try { - List topics = Collections.singletonList("topic_meters"); - consumer.subscribe(topics); for (int i = 0; i < 50; i++) { ConsumerRecords records = consumer.poll(Duration.ofMillis(100)); for (ConsumerRecord record : records) { ResultBean bean = record.value(); - // process your data here + // Add your data processing logic here System.out.println("data: " + JSON.toJSONString(bean)); } if (!records.isEmpty()) { @@ -138,7 +145,10 @@ public class WsConsumerLoopFull { } } catch (Exception ex) { // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to execute commit example, %sErrMessage: %s%n", + System.out.printf("Failed to commit offset, topic: %s, groupId: %s, clientId: %s, %sErrMessage: %s%n", + topics.get(0), + groupId, + clientId, ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", ex.getMessage()); // Print stack trace for context in examples. Use logging in production. @@ -158,7 +168,10 @@ public class WsConsumerLoopFull { System.out.println("Consumer unsubscribed successfully."); } catch (Exception ex) { // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to unsubscribe consumer, %sErrMessage: %s%n", + System.out.printf("Failed to unsubscribe consumer, topic: %s, groupId: %s, clientId: %s, %sErrMessage: %s%n", + topics.get(0), + groupId, + clientId, ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", ex.getMessage()); // Print stack trace for context in examples. Use logging in production. diff --git a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ConsumerLoopFull.java b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ConsumerLoopFull.java deleted file mode 100644 index ce9af5ecdc..0000000000 --- a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ConsumerLoopFull.java +++ /dev/null @@ -1,384 +0,0 @@ -package com.taosdata.example; - -import com.alibaba.fastjson.JSON; -import com.taosdata.jdbc.TSDBDriver; -import com.taosdata.jdbc.tmq.*; - -import java.sql.*; -import java.time.Duration; -import java.util.Collections; -import java.util.List; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -// ANCHOR: consumer_demo -public class ConsumerLoopFull { - static private Connection connection; - static private Statement statement; - static private volatile boolean stopThread = false; - - public static TaosConsumer getConsumer() throws Exception { -// ANCHOR: create_consumer - Properties config = new Properties(); - config.setProperty("td.connect.type", "jni"); - config.setProperty("bootstrap.servers", "localhost:6030"); - config.setProperty("auto.offset.reset", "latest"); - config.setProperty("msg.with.table.name", "true"); - config.setProperty("enable.auto.commit", "true"); - config.setProperty("auto.commit.interval.ms", "1000"); - config.setProperty("group.id", "group1"); - config.setProperty("client.id", "1"); - config.setProperty("td.connect.user", "root"); - config.setProperty("td.connect.pass", "taosdata"); - config.setProperty("value.deserializer", "com.taosdata.example.ConsumerLoopFull$ResultDeserializer"); - config.setProperty("value.deserializer.encoding", "UTF-8"); - - try { - TaosConsumer consumer= new TaosConsumer<>(config); - System.out.printf("Create consumer successfully, host: %s, groupId: %s, clientId: %s%n", - config.getProperty("bootstrap.servers"), - config.getProperty("group.id"), - config.getProperty("client.id")); - return consumer; - } catch (Exception ex) { - // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to create native consumer, host: %s, %sErrMessage: %s%n", - config.getProperty("bootstrap.servers"), - ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", - ex.getMessage()); - // Print stack trace for context in examples. Use logging in production. - ex.printStackTrace(); - throw ex; - } -// ANCHOR_END: create_consumer - } - - public static void pollExample(TaosConsumer consumer) throws SQLException { -// ANCHOR: poll_data_code_piece - try { - List topics = Collections.singletonList("topic_meters"); - - // subscribe to the topics - consumer.subscribe(topics); - System.out.println("Subscribe topics successfully."); - for (int i = 0; i < 50; i++) { - // poll data - ConsumerRecords records = consumer.poll(Duration.ofMillis(100)); - for (ConsumerRecord record : records) { - ResultBean bean = record.value(); - // process the data here - System.out.println("data: " + JSON.toJSONString(bean)); - } - } - } catch (Exception ex) { - // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to poll data, %sErrMessage: %s%n", - ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", - ex.getMessage()); - // Print stack trace for context in examples. Use logging in production. - ex.printStackTrace(); - throw ex; - } -// ANCHOR_END: poll_data_code_piece - } - - public static void seekExample(TaosConsumer consumer) throws SQLException { -// ANCHOR: consumer_seek - try { - List topics = Collections.singletonList("topic_meters"); - - // subscribe to the topics - consumer.subscribe(topics); - System.out.println("Subscribe topics successfully."); - Set assignment = consumer.assignment(); - System.out.println("Now assignment: " + JSON.toJSONString(assignment)); - - ConsumerRecords records = ConsumerRecords.emptyRecord(); - // make sure we have got some data - while (records.isEmpty()) { - records = consumer.poll(Duration.ofMillis(100)); - } - - consumer.seekToBeginning(assignment); - System.out.println("Assignment seek to beginning successfully."); - } catch (Exception ex) { - // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to execute seek example, %sErrMessage: %s%n", - ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", - ex.getMessage()); - // Print stack trace for context in examples. Use logging in production. - ex.printStackTrace(); - throw ex; - } -// ANCHOR_END: consumer_seek - } - - - public static void commitExample(TaosConsumer consumer) throws SQLException { -// ANCHOR: commit_code_piece - try { - List topics = Collections.singletonList("topic_meters"); - - consumer.subscribe(topics); - for (int i = 0; i < 50; i++) { - ConsumerRecords records = consumer.poll(Duration.ofMillis(100)); - for (ConsumerRecord record : records) { - ResultBean bean = record.value(); - // process your data here - System.out.println("data: " + JSON.toJSONString(bean)); - } - if (!records.isEmpty()) { - // after processing the data, commit the offset manually - consumer.commitSync(); - System.out.println("Commit offset manually successfully."); - } - } - } catch (Exception ex) { - // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to execute commit example, %sErrMessage: %s%n", - ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", - ex.getMessage()); - // Print stack trace for context in examples. Use logging in production. - ex.printStackTrace(); - throw ex; - } -// ANCHOR_END: commit_code_piece - } - - public static void unsubscribeExample(TaosConsumer consumer) throws SQLException { - List topics = Collections.singletonList("topic_meters"); - consumer.subscribe(topics); -// ANCHOR: unsubscribe_data_code_piece - try { - // unsubscribe the consumer - consumer.unsubscribe(); - System.out.println("Consumer unsubscribed successfully."); - } catch (Exception ex) { - // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to unsubscribe consumer, %sErrMessage: %s%n", - ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", - ex.getMessage()); - // Print stack trace for context in examples. Use logging in production. - ex.printStackTrace(); - throw ex; - } - finally { - // close the consumer - consumer.close(); - System.out.println("Consumer closed successfully."); - } -// ANCHOR_END: unsubscribe_data_code_piece - } - - public static class ResultDeserializer extends ReferenceDeserializer { - - } - - // use this class to define the data structure of the result record - public static class ResultBean { - private Timestamp ts; - private double current; - private int voltage; - private double phase; - private int groupid; - private String location; - - public Timestamp getTs() { - return ts; - } - - public void setTs(Timestamp ts) { - this.ts = ts; - } - - public double getCurrent() { - return current; - } - - public void setCurrent(double current) { - this.current = current; - } - - public int getVoltage() { - return voltage; - } - - public void setVoltage(int voltage) { - this.voltage = voltage; - } - - public double getPhase() { - return phase; - } - - public void setPhase(double phase) { - this.phase = phase; - } - - public int getGroupid() { - return groupid; - } - - public void setGroupid(int groupid) { - this.groupid = groupid; - } - - public String getLocation() { - return location; - } - - public void setLocation(String location) { - this.location = location; - } - } - - public static void prepareData() throws SQLException, InterruptedException { - try { - int i = 0; - while (!stopThread) { - String insertQuery = "INSERT INTO power.d1001 USING power.meters TAGS(2,'California.SanFrancisco') VALUES (NOW + " + i + "a, 10.30000, 219, 0.31000) "; - int affectedRows = statement.executeUpdate(insertQuery); - assert affectedRows == 1; - i++; - Thread.sleep(1); - } - } catch (Exception ex) { - // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to insert data to power.meters, %sErrMessage: %s%n", - ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", - ex.getMessage()); - // Print stack trace for context in examples. Use logging in production. - ex.printStackTrace(); - throw ex; - } - } - - public static void prepareMeta() throws SQLException { - try { - statement.executeUpdate("CREATE DATABASE IF NOT EXISTS power"); - statement.executeUpdate("USE power"); - statement.executeUpdate("CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))"); - statement.executeUpdate("CREATE TOPIC IF NOT EXISTS topic_meters AS SELECT ts, current, voltage, phase, groupid, location FROM meters"); - } catch (Exception ex) { - // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to create db and table, %sErrMessage: %s%n", - ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", - ex.getMessage()); - // Print stack trace for context in examples. Use logging in production. - ex.printStackTrace(); - throw ex; - } - } - - public static void initConnection() throws SQLException { - String url = "jdbc:TAOS://localhost:6030?user=root&password=taosdata"; - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "C"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - - try { - connection = DriverManager.getConnection(url, properties); - } catch (SQLException ex) { - System.out.println("Failed to create connection, url:" + url + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to create connection", ex); - } - try { - statement = connection.createStatement(); - } catch (SQLException ex) { - System.out.println("Failed to create statement, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to create statement", ex); - } - System.out.println("Connection created successfully."); - } - - public static void closeConnection() throws SQLException { - try { - if (statement != null) { - statement.close(); - } - } catch (SQLException ex) { - System.out.println("Failed to close statement, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to close statement", ex); - } - - try { - if (connection != null) { - connection.close(); - } - } catch (SQLException ex) { - System.out.println("Failed to close connection, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to close connection", ex); - } - System.out.println("Connection closed Successfully."); - } - - - public static void main(String[] args) throws SQLException, InterruptedException { - initConnection(); - prepareMeta(); - - // create a single thread executor - ExecutorService executor = Executors.newSingleThreadExecutor(); - - // submit a task - executor.submit(() -> { - try { - prepareData(); - } catch (SQLException ex) { - System.out.println("Failed to prepare data, ErrCode:" + ex.getErrorCode() + ", ErrMessage: " + ex.getMessage()); - return; - } catch (Exception ex) { - System.out.println("Failed to prepare data, ErrMessage: " + ex.getMessage()); - return; - } - System.out.println("pollDataExample executed successfully."); - }); - - try { - TaosConsumer consumer = getConsumer(); - - pollExample(consumer); - System.out.println("pollExample executed successfully."); - consumer.unsubscribe(); - - seekExample(consumer); - System.out.println("seekExample executed successfully."); - consumer.unsubscribe(); - - commitExample(consumer); - System.out.println("commitExample executed successfully."); - consumer.unsubscribe(); - - unsubscribeExample(consumer); - System.out.println("unsubscribeExample executed successfully"); - } catch (SQLException ex) { - System.out.println("Failed to poll data from topic_meters, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - return; - } catch (Exception ex) { - System.out.println("Failed to poll data from topic_meters, ErrMessage: " + ex.getMessage()); - return; - } - - stopThread = true; - // close the executor, which will make the executor reject new tasks - executor.shutdown(); - - try { - // wait for the executor to terminate - boolean result = executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); - assert result; - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("Wait executor termination failed."); - } - - closeConnection(); - System.out.println("program end."); - } -} -// ANCHOR_END: consumer_demo diff --git a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcCreatDBDemo.java b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcCreatDBDemo.java deleted file mode 100644 index 28d7d2d67b..0000000000 --- a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcCreatDBDemo.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.taosdata.example; - -import com.taosdata.jdbc.AbstractStatement; - -import java.sql.*; -import java.util.Properties; - -public class JdbcCreatDBDemo { - private static final String host = "localhost"; - private static final String dbName = "test"; - private static final String tbName = "weather"; - private static final String user = "root"; - private static final String password = "taosdata"; - - - public static void main(String[] args) throws SQLException { - - final String jdbcUrl = "jdbc:TAOS://" + host + ":6030/?user=" + user + "&password=" + password; - -// get connection - Properties properties = new Properties(); - properties.setProperty("charset", "UTF-8"); - properties.setProperty("locale", "en_US.UTF-8"); - properties.setProperty("timezone", "UTC-8"); - System.out.println("get connection starting..."); -// ANCHOR: create_db_and_table - try (Connection connection = DriverManager.getConnection(jdbcUrl, properties); - Statement stmt = connection.createStatement()) { - - // create database - int rowsAffected = stmt.executeUpdate("CREATE DATABASE IF NOT EXISTS power"); - // you can check rowsAffected here - System.out.println("Create database power successfully, rowsAffected: " + rowsAffected); - // create table - rowsAffected = stmt.executeUpdate("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))"); - // you can check rowsAffected here - System.out.println("Create stable power.meters successfully, rowsAffected: " + rowsAffected); - } catch (Exception ex) { - // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to create database power or stable meters, %sErrMessage: %s%n", - ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", - ex.getMessage()); - // Print stack trace for context in examples. Use logging in production. - ex.printStackTrace(); - throw ex; - } -// ANCHOR_END: create_db_and_table - - } - - private static void printResult(ResultSet resultSet) throws SQLException { - Util.printResult(resultSet); - } - -} diff --git a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcInsertDataDemo.java b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcInsertDataDemo.java deleted file mode 100644 index 08798b755c..0000000000 --- a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcInsertDataDemo.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.taosdata.example; - -import com.taosdata.jdbc.AbstractStatement; - -import java.sql.*; -import java.util.Properties; - -public class JdbcInsertDataDemo { - private static final String host = "localhost"; - private static final String dbName = "test"; - private static final String tbName = "weather"; - private static final String user = "root"; - private static final String password = "taosdata"; - - - public static void main(String[] args) throws SQLException { - - final String jdbcUrl = "jdbc:TAOS://" + host + ":6030/?user=" + user + "&password=" + password; - -// get connection - Properties properties = new Properties(); - properties.setProperty("charset", "UTF-8"); - properties.setProperty("locale", "en_US.UTF-8"); - properties.setProperty("timezone", "UTC-8"); - System.out.println("get connection starting..."); -// ANCHOR: insert_data - try (Connection connection = DriverManager.getConnection(jdbcUrl, properties); - Statement stmt = connection.createStatement()) { - - // insert data, please make sure the database and table are created before - String insertQuery = "INSERT INTO " + - "power.d1001 USING power.meters TAGS(2,'California.SanFrancisco') " + - "VALUES " + - "(NOW + 1a, 10.30000, 219, 0.31000) " + - "(NOW + 2a, 12.60000, 218, 0.33000) " + - "(NOW + 3a, 12.30000, 221, 0.31000) " + - "power.d1002 USING power.meters TAGS(3, 'California.SanFrancisco') " + - "VALUES " + - "(NOW + 1a, 10.30000, 218, 0.25000) "; - int affectedRows = stmt.executeUpdate(insertQuery); - // you can check affectedRows here - System.out.println("Successfully inserted " + affectedRows + " rows to power.meters."); - } catch (Exception ex) { - // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to insert data to power.meters, %sErrMessage: %s%n", - ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", - ex.getMessage()); - // Print stack trace for context in examples. Use logging in production. - ex.printStackTrace(); - throw ex; - } -// ANCHOR_END: insert_data - } -} diff --git a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcQueryDemo.java b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcQueryDemo.java deleted file mode 100644 index 768ba8929c..0000000000 --- a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcQueryDemo.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.taosdata.example; - -import com.taosdata.jdbc.AbstractStatement; - -import java.sql.*; -import java.util.Properties; - -public class JdbcQueryDemo { - private static final String host = "localhost"; - private static final String dbName = "test"; - private static final String tbName = "weather"; - private static final String user = "root"; - private static final String password = "taosdata"; - - - public static void main(String[] args) throws SQLException { - - final String jdbcUrl = "jdbc:TAOS://" + host + ":6030/?user=" + user + "&password=" + password; - -// get connection - Properties properties = new Properties(); - properties.setProperty("charset", "UTF-8"); - properties.setProperty("locale", "en_US.UTF-8"); - properties.setProperty("timezone", "UTC-8"); - System.out.println("get connection starting..."); -// ANCHOR: query_data - String sql = "SELECT ts, current, location FROM power.meters limit 100"; - try (Connection connection = DriverManager.getConnection(jdbcUrl, properties); - Statement stmt = connection.createStatement(); - // query data, make sure the database and table are created before - ResultSet resultSet = stmt.executeQuery(sql)) { - - Timestamp ts; - float current; - String location; - while (resultSet.next()) { - ts = resultSet.getTimestamp(1); - current = resultSet.getFloat(2); - // we recommend using the column name to get the value - location = resultSet.getString("location"); - - // you can check data here - System.out.printf("ts: %s, current: %f, location: %s %n", ts, current, location); - } - } catch (Exception ex) { - // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to query data from power.meters, sql: %s, %sErrMessage: %s%n", - sql, - ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", - ex.getMessage()); - // Print stack trace for context in examples. Use logging in production. - ex.printStackTrace(); - throw ex; - } -// ANCHOR_END: query_data - } -} diff --git a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcReqIdDemo.java b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcReqIdDemo.java deleted file mode 100644 index dd4b549bc5..0000000000 --- a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/JdbcReqIdDemo.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.taosdata.example; - -import com.taosdata.jdbc.AbstractStatement; - -import java.sql.*; -import java.util.Properties; - -public class JdbcReqIdDemo { - private static final String host = "localhost"; - private static final String dbName = "test"; - private static final String tbName = "weather"; - private static final String user = "root"; - private static final String password = "taosdata"; - - - public static void main(String[] args) throws SQLException { - - final String jdbcUrl = "jdbc:TAOS://" + host + ":6030/?user=" + user + "&password=" + password; - -// get connection - Properties properties = new Properties(); - properties.setProperty("charset", "UTF-8"); - properties.setProperty("locale", "en_US.UTF-8"); - properties.setProperty("timezone", "UTC-8"); - System.out.println("get connection starting..."); - -// ANCHOR: with_reqid - long reqId = 3L; - try (Connection connection = DriverManager.getConnection(jdbcUrl, properties); - // Create a statement that allows specifying a request ID - AbstractStatement aStmt = (AbstractStatement) connection.createStatement()) { - - try (ResultSet resultSet = aStmt.executeQuery("SELECT ts, current, location FROM power.meters limit 1", reqId)) { - Timestamp ts; - float current; - String location; - while (resultSet.next()) { - ts = resultSet.getTimestamp(1); - current = resultSet.getFloat(2); - // we recommend using the column name to get the value - location = resultSet.getString("location"); - - // you can check data here - System.out.printf("ts: %s, current: %f, location: %s %n", ts, current, location); - - } - } - } catch (Exception ex) { - // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to execute sql with reqId: %s, %sErrMessage: %s%n", reqId, - ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", - ex.getMessage()); - // Print stack trace for context in examples. Use logging in production. - ex.printStackTrace(); - throw ex; - } -// ANCHOR_END: with_reqid - } - - private static void printResult(ResultSet resultSet) throws SQLException { - Util.printResult(resultSet); - } - -} diff --git a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ParameterBindingBasicDemo.java b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ParameterBindingBasicDemo.java deleted file mode 100644 index b5732f0e33..0000000000 --- a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ParameterBindingBasicDemo.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.taosdata.example; - -import com.taosdata.jdbc.TSDBPreparedStatement; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.Random; - -// ANCHOR: para_bind -public class ParameterBindingBasicDemo { - - // modify host to your own - private static final String host = "127.0.0.1"; - private static final Random random = new Random(System.currentTimeMillis()); - private static final int numOfSubTable = 10, numOfRow = 10; - - public static void main(String[] args) throws SQLException { - - String jdbcUrl = "jdbc:TAOS://" + host + ":6030/"; - try (Connection conn = DriverManager.getConnection(jdbcUrl, "root", "taosdata")) { - - init(conn); - - String sql = "INSERT INTO ? USING power.meters TAGS(?,?) VALUES (?,?,?,?)"; - - try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) { - - for (int i = 1; i <= numOfSubTable; i++) { - // set table name - pstmt.setTableName("d_bind_" + i); - - // set tags - pstmt.setTagInt(0, i); - pstmt.setTagString(1, "location_" + i); - - // set column ts - ArrayList tsList = new ArrayList<>(); - long current = System.currentTimeMillis(); - for (int j = 0; j < numOfRow; j++) - tsList.add(current + j); - pstmt.setTimestamp(0, tsList); - - // set column current - ArrayList currentList = new ArrayList<>(); - for (int j = 0; j < numOfRow; j++) - currentList.add(random.nextFloat() * 30); - pstmt.setFloat(1, currentList); - - // set column voltage - ArrayList voltageList = new ArrayList<>(); - for (int j = 0; j < numOfRow; j++) - voltageList.add(random.nextInt(300)); - pstmt.setInt(2, voltageList); - - // set column phase - ArrayList phaseList = new ArrayList<>(); - for (int j = 0; j < numOfRow; j++) - phaseList.add(random.nextFloat()); - pstmt.setFloat(3, phaseList); - // add column - pstmt.columnDataAddBatch(); - } - // execute column - pstmt.columnDataExecuteBatch(); - // you can check exeResult here - System.out.println("Successfully inserted " + (numOfSubTable * numOfRow) + " rows to power.meters."); - } - } catch (Exception ex) { - // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to insert to table meters using stmt, %sErrMessage: %s%n", - ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", - ex.getMessage()); - // Print stack trace for context in examples. Use logging in production. - ex.printStackTrace(); - throw ex; - } - } - - private static void init(Connection conn) throws SQLException { - try (Statement stmt = conn.createStatement()) { - stmt.execute("CREATE DATABASE IF NOT EXISTS power"); - stmt.execute("USE power"); - stmt.execute("CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))"); - } - } -} -// ANCHOR_END: para_bind diff --git a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/SchemalessJniTest.java b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/SchemalessJniTest.java deleted file mode 100644 index 5b1ce51be6..0000000000 --- a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/SchemalessJniTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.taosdata.example; - -import com.taosdata.jdbc.AbstractConnection; -import com.taosdata.jdbc.enums.SchemalessProtocolType; -import com.taosdata.jdbc.enums.SchemalessTimestampType; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.sql.Statement; - -// ANCHOR: schemaless -public class SchemalessJniTest { - private static final String host = "127.0.0.1"; - private static final String lineDemo = "meters,groupid=2,location=California.SanFrancisco current=10.3000002f64,voltage=219i32,phase=0.31f64 1626006833639"; - private static final String telnetDemo = "metric_telnet 1707095283260 4 host=host0 interface=eth0"; - private static final String jsonDemo = "{\"metric\": \"metric_json\",\"timestamp\": 1626846400,\"value\": 10.3, \"tags\": {\"groupid\": 2, \"location\": \"California.SanFrancisco\", \"id\": \"d1001\"}}"; - - public static void main(String[] args) throws SQLException { - final String jdbcUrl = "jdbc:TAOS://" + host + ":6030/?user=root&password=taosdata"; - try (Connection connection = DriverManager.getConnection(jdbcUrl)) { - init(connection); - AbstractConnection conn = connection.unwrap(AbstractConnection.class); - - conn.write(lineDemo, SchemalessProtocolType.LINE, SchemalessTimestampType.MILLI_SECONDS); - conn.write(telnetDemo, SchemalessProtocolType.TELNET, SchemalessTimestampType.MILLI_SECONDS); - conn.write(jsonDemo, SchemalessProtocolType.JSON, SchemalessTimestampType.NOT_CONFIGURED); - System.out.println("Inserted data with schemaless successfully."); - } catch (Exception ex) { - // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to insert data with schemaless, %sErrMessage: %s%n", - ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", - ex.getMessage()); - // Print stack trace for context in examples. Use logging in production. - ex.printStackTrace(); - throw ex; - } - } - - private static void init(Connection connection) throws SQLException { - try (Statement stmt = connection.createStatement()) { - stmt.execute("CREATE DATABASE IF NOT EXISTS power"); - stmt.execute("USE power"); - } - } -} -// ANCHOR_END: schemaless diff --git a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/SchemalessWsTest.java b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/SchemalessWsTest.java deleted file mode 100644 index 0f15e70224..0000000000 --- a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/SchemalessWsTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.taosdata.example; - -import com.taosdata.jdbc.AbstractConnection; -import com.taosdata.jdbc.enums.SchemalessProtocolType; -import com.taosdata.jdbc.enums.SchemalessTimestampType; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.sql.Statement; - -// ANCHOR: schemaless -public class SchemalessWsTest { - private static final String host = "127.0.0.1"; - private static final String lineDemo = "meters,groupid=2,location=California.SanFrancisco current=10.3000002f64,voltage=219i32,phase=0.31f64 1626006833639"; - private static final String telnetDemo = "metric_telnet 1707095283260 4 host=host0 interface=eth0"; - private static final String jsonDemo = "{\"metric\": \"metric_json\",\"timestamp\": 1626846400,\"value\": 10.3, \"tags\": {\"groupid\": 2, \"location\": \"California.SanFrancisco\", \"id\": \"d1001\"}}"; - - public static void main(String[] args) throws SQLException { - final String url = "jdbc:TAOS-RS://" + host + ":6041?user=root&password=taosdata&batchfetch=true"; - try(Connection connection = DriverManager.getConnection(url)){ - init(connection); - AbstractConnection conn = connection.unwrap(AbstractConnection.class); - - conn.write(lineDemo, SchemalessProtocolType.LINE, SchemalessTimestampType.MILLI_SECONDS); - conn.write(telnetDemo, SchemalessProtocolType.TELNET, SchemalessTimestampType.MILLI_SECONDS); - conn.write(jsonDemo, SchemalessProtocolType.JSON, SchemalessTimestampType.SECONDS); - System.out.println("Inserted data with schemaless successfully."); - } catch (Exception ex) { - // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to insert data with schemaless, %sErrMessage: %s%n", - ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", - ex.getMessage()); - // Print stack trace for context in examples. Use logging in production. - ex.printStackTrace(); - throw ex; - } - } - - private static void init(Connection connection) throws SQLException { - try (Statement stmt = connection.createStatement()) { - stmt.execute("CREATE DATABASE IF NOT EXISTS power"); - stmt.execute("USE power"); - } - } -} -// ANCHOR_END: schemaless diff --git a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WSParameterBindingBasicDemo.java b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WSParameterBindingBasicDemo.java deleted file mode 100644 index 792ee4ed2d..0000000000 --- a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WSParameterBindingBasicDemo.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.taosdata.example; - -import com.taosdata.jdbc.TSDBPreparedStatement; -import com.taosdata.jdbc.ws.TSWSPreparedStatement; - -import java.sql.*; -import java.util.ArrayList; -import java.util.Random; - -// ANCHOR: para_bind -public class WSParameterBindingBasicDemo { - - // modify host to your own - private static final String host = "127.0.0.1"; - private static final Random random = new Random(System.currentTimeMillis()); - private static final int numOfSubTable = 10, numOfRow = 10; - - public static void main(String[] args) throws SQLException { - - String jdbcUrl = "jdbc:TAOS-RS://" + host + ":6041/?batchfetch=true"; - try (Connection conn = DriverManager.getConnection(jdbcUrl, "root", "taosdata")) { - init(conn); - - String sql = "INSERT INTO ? USING power.meters TAGS(?,?) VALUES (?,?,?,?)"; - - try (TSWSPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSWSPreparedStatement.class)) { - - for (int i = 1; i <= numOfSubTable; i++) { - // set table name - pstmt.setTableName("d_bind_" + i); - - // set tags - pstmt.setTagInt(0, i); - pstmt.setTagString(1, "location_" + i); - - // set columns - long current = System.currentTimeMillis(); - for (int j = 0; j < numOfRow; j++) { - pstmt.setTimestamp(1, new Timestamp(current + j)); - pstmt.setFloat(2, random.nextFloat() * 30); - pstmt.setInt(3, random.nextInt(300)); - pstmt.setFloat(4, random.nextFloat()); - pstmt.addBatch(); - } - int [] exeResult = pstmt.executeBatch(); - // you can check exeResult here - System.out.println("Successfully inserted " + exeResult.length + " rows to power.meters."); - } - } - } catch (Exception ex) { - // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to insert to table meters using stmt, %sErrMessage: %s%n", - ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", - ex.getMessage()); - // Print stack trace for context in examples. Use logging in production. - ex.printStackTrace(); - throw ex; - } - } - - private static void init(Connection conn) throws SQLException { - try (Statement stmt = conn.createStatement()) { - stmt.execute("CREATE DATABASE IF NOT EXISTS power"); - stmt.execute("USE power"); - stmt.execute("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))"); - } - } -} -// ANCHOR_END: para_bind diff --git a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WsConsumerLoopFull.java b/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WsConsumerLoopFull.java deleted file mode 100644 index 17380023cd..0000000000 --- a/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WsConsumerLoopFull.java +++ /dev/null @@ -1,384 +0,0 @@ -package com.taosdata.example; - -import com.alibaba.fastjson.JSON; -import com.taosdata.jdbc.TSDBDriver; -import com.taosdata.jdbc.tmq.*; - -import java.sql.*; -import java.time.Duration; -import java.util.Collections; -import java.util.List; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -// ANCHOR: consumer_demo -public class WsConsumerLoopFull { - static private Connection connection; - static private Statement statement; - static private volatile boolean stopThread = false; - - public static TaosConsumer getConsumer() throws Exception { -// ANCHOR: create_consumer - Properties config = new Properties(); - config.setProperty("td.connect.type", "ws"); - config.setProperty("bootstrap.servers", "localhost:6041"); - config.setProperty("auto.offset.reset", "latest"); - config.setProperty("msg.with.table.name", "true"); - config.setProperty("enable.auto.commit", "true"); - config.setProperty("auto.commit.interval.ms", "1000"); - config.setProperty("group.id", "group1"); - config.setProperty("client.id", "1"); - config.setProperty("td.connect.user", "root"); - config.setProperty("td.connect.pass", "taosdata"); - config.setProperty("value.deserializer", "com.taosdata.example.WsConsumerLoopFull$ResultDeserializer"); - config.setProperty("value.deserializer.encoding", "UTF-8"); - - try { - TaosConsumer consumer= new TaosConsumer<>(config); - System.out.printf("Create consumer successfully, host: %s, groupId: %s, clientId: %s%n", - config.getProperty("bootstrap.servers"), - config.getProperty("group.id"), - config.getProperty("client.id")); - return consumer; - } catch (Exception ex) { - // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to create websocket consumer, host: %s, %sErrMessage: %s%n", - config.getProperty("bootstrap.servers"), - ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", - ex.getMessage()); - // Print stack trace for context in examples. Use logging in production. - ex.printStackTrace(); - throw ex; - } -// ANCHOR_END: create_consumer - } - - public static void pollExample(TaosConsumer consumer) throws SQLException { -// ANCHOR: poll_data_code_piece - try { - List topics = Collections.singletonList("topic_meters"); - - // subscribe to the topics - consumer.subscribe(topics); - System.out.println("Subscribe topics successfully."); - for (int i = 0; i < 50; i++) { - // poll data - ConsumerRecords records = consumer.poll(Duration.ofMillis(100)); - for (ConsumerRecord record : records) { - ResultBean bean = record.value(); - // process the data here - System.out.println("data: " + JSON.toJSONString(bean)); - } - } - } catch (Exception ex) { - // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to poll data, %sErrMessage: %s%n", - ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", - ex.getMessage()); - // Print stack trace for context in examples. Use logging in production. - ex.printStackTrace(); - throw ex; - } -// ANCHOR_END: poll_data_code_piece - } - - public static void seekExample(TaosConsumer consumer) throws SQLException { -// ANCHOR: consumer_seek - try { - List topics = Collections.singletonList("topic_meters"); - - // subscribe to the topics - consumer.subscribe(topics); - System.out.println("Subscribe topics successfully."); - Set assignment = consumer.assignment(); - System.out.println("Now assignment: " + JSON.toJSONString(assignment)); - - ConsumerRecords records = ConsumerRecords.emptyRecord(); - // make sure we have got some data - while (records.isEmpty()) { - records = consumer.poll(Duration.ofMillis(100)); - } - - consumer.seekToBeginning(assignment); - System.out.println("Assignment seek to beginning successfully."); - } catch (Exception ex) { - // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to execute seek example, %sErrMessage: %s%n", - ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", - ex.getMessage()); - // Print stack trace for context in examples. Use logging in production. - ex.printStackTrace(); - throw ex; - } -// ANCHOR_END: consumer_seek - } - - - public static void commitExample(TaosConsumer consumer) throws SQLException { -// ANCHOR: commit_code_piece - try { - List topics = Collections.singletonList("topic_meters"); - - consumer.subscribe(topics); - for (int i = 0; i < 50; i++) { - ConsumerRecords records = consumer.poll(Duration.ofMillis(100)); - for (ConsumerRecord record : records) { - ResultBean bean = record.value(); - // process your data here - System.out.println("data: " + JSON.toJSONString(bean)); - } - if (!records.isEmpty()) { - // after processing the data, commit the offset manually - consumer.commitSync(); - System.out.println("Commit offset manually successfully."); - } - } - } catch (Exception ex) { - // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to execute commit example, %sErrMessage: %s%n", - ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", - ex.getMessage()); - // Print stack trace for context in examples. Use logging in production. - ex.printStackTrace(); - throw ex; - } -// ANCHOR_END: commit_code_piece - } - - public static void unsubscribeExample(TaosConsumer consumer) throws SQLException { - List topics = Collections.singletonList("topic_meters"); - consumer.subscribe(topics); -// ANCHOR: unsubscribe_data_code_piece - try { - // unsubscribe the consumer - consumer.unsubscribe(); - System.out.println("Consumer unsubscribed successfully."); - } catch (Exception ex) { - // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to unsubscribe consumer, %sErrMessage: %s%n", - ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", - ex.getMessage()); - // Print stack trace for context in examples. Use logging in production. - ex.printStackTrace(); - throw ex; - } - finally { - // close the consumer - consumer.close(); - System.out.println("Consumer closed successfully."); - } -// ANCHOR_END: unsubscribe_data_code_piece - } - - public static class ResultDeserializer extends ReferenceDeserializer { - - } - - // use this class to define the data structure of the result record - public static class ResultBean { - private Timestamp ts; - private double current; - private int voltage; - private double phase; - private int groupid; - private String location; - - public Timestamp getTs() { - return ts; - } - - public void setTs(Timestamp ts) { - this.ts = ts; - } - - public double getCurrent() { - return current; - } - - public void setCurrent(double current) { - this.current = current; - } - - public int getVoltage() { - return voltage; - } - - public void setVoltage(int voltage) { - this.voltage = voltage; - } - - public double getPhase() { - return phase; - } - - public void setPhase(double phase) { - this.phase = phase; - } - - public int getGroupid() { - return groupid; - } - - public void setGroupid(int groupid) { - this.groupid = groupid; - } - - public String getLocation() { - return location; - } - - public void setLocation(String location) { - this.location = location; - } - } - - public static void prepareData() throws SQLException, InterruptedException { - try { - int i = 0; - while (!stopThread) { - String insertQuery = "INSERT INTO power.d1001 USING power.meters TAGS(2,'California.SanFrancisco') VALUES (NOW + " + i + "a, 10.30000, 219, 0.31000) "; - int affectedRows = statement.executeUpdate(insertQuery); - assert affectedRows == 1; - i++; - Thread.sleep(1); - } - } catch (Exception ex) { - // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to insert data to power.meters, %sErrMessage: %s%n", - ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", - ex.getMessage()); - // Print stack trace for context in examples. Use logging in production. - ex.printStackTrace(); - throw ex; - } - } - - public static void prepareMeta() throws SQLException { - try { - statement.executeUpdate("CREATE DATABASE IF NOT EXISTS power"); - statement.executeUpdate("USE power"); - statement.executeUpdate("CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))"); - statement.executeUpdate("CREATE TOPIC IF NOT EXISTS topic_meters AS SELECT ts, current, voltage, phase, groupid, location FROM meters"); - } catch (Exception ex) { - // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to create db and table, %sErrMessage: %s%n", - ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "", - ex.getMessage()); - // Print stack trace for context in examples. Use logging in production. - ex.printStackTrace(); - throw ex; - } - } - - public static void initConnection() throws SQLException { - String url = "jdbc:TAOS://localhost:6030?user=root&password=taosdata"; - Properties properties = new Properties(); - properties.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "C"); - properties.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); - - try { - connection = DriverManager.getConnection(url, properties); - } catch (SQLException ex) { - System.out.println("Failed to create connection, url:" + url + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to create connection", ex); - } - try { - statement = connection.createStatement(); - } catch (SQLException ex) { - System.out.println("Failed to create statement, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to create statement", ex); - } - System.out.println("Connection created successfully."); - } - - public static void closeConnection() throws SQLException { - try { - if (statement != null) { - statement.close(); - } - } catch (SQLException ex) { - System.out.println("Failed to close statement, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to close statement", ex); - } - - try { - if (connection != null) { - connection.close(); - } - } catch (SQLException ex) { - System.out.println("Failed to close connection, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - throw new SQLException("Failed to close connection", ex); - } - System.out.println("Connection closed Successfully."); - } - - - public static void main(String[] args) throws SQLException, InterruptedException { - initConnection(); - prepareMeta(); - - // create a single thread executor - ExecutorService executor = Executors.newSingleThreadExecutor(); - - // submit a task - executor.submit(() -> { - try { - prepareData(); - } catch (SQLException ex) { - System.out.println("Failed to prepare data, ErrCode:" + ex.getErrorCode() + ", ErrMessage: " + ex.getMessage()); - return; - } catch (Exception ex) { - System.out.println("Failed to prepare data, ErrMessage: " + ex.getMessage()); - return; - } - System.out.println("pollDataExample executed successfully."); - }); - - try { - TaosConsumer consumer = getConsumer(); - - pollExample(consumer); - System.out.println("pollExample executed successfully."); - consumer.unsubscribe(); - - seekExample(consumer); - System.out.println("seekExample executed successfully."); - consumer.unsubscribe(); - - commitExample(consumer); - System.out.println("commitExample executed successfully."); - consumer.unsubscribe(); - - unsubscribeExample(consumer); - System.out.println("unsubscribeExample executed successfully"); - } catch (SQLException ex) { - System.out.println("Failed to poll data from topic_meters, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage()); - return; - } catch (Exception ex) { - System.out.println("Failed to poll data from topic_meters, ErrMessage: " + ex.getMessage()); - return; - } - - stopThread = true; - // close the executor, which will make the executor reject new tasks - executor.shutdown(); - - try { - // wait for the executor to terminate - boolean result = executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); - assert result; - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("Wait executor termination failed."); - } - - closeConnection(); - System.out.println("program end."); - } -} -// ANCHOR_END: consumer_demo From d6284424b66b854dc4d63398baa0438b50c49297 Mon Sep 17 00:00:00 2001 From: t_max <1172915550@qq.com> Date: Fri, 16 Aug 2024 15:08:14 +0800 Subject: [PATCH 11/22] docs: update the output of go and c# examples --- docs/examples/csharp/subscribe/Program.cs | 114 +++++-- docs/examples/csharp/wsInsert/Program.cs | 65 ++-- docs/examples/csharp/wssubscribe/Program.cs | 110 +++++-- docs/examples/go/queryreqid/main.go | 118 +++---- docs/examples/go/sqlquery/main.go | 172 +++++----- docs/examples/go/tmq/native/main.go | 315 ++++++++++-------- docs/examples/go/tmq/ws/main.go | 338 ++++++++++++-------- 7 files changed, 737 insertions(+), 495 deletions(-) diff --git a/docs/examples/csharp/subscribe/Program.cs b/docs/examples/csharp/subscribe/Program.cs index 4138194800..2ec73aae48 100644 --- a/docs/examples/csharp/subscribe/Program.cs +++ b/docs/examples/csharp/subscribe/Program.cs @@ -6,6 +6,11 @@ namespace TMQExample { internal class SubscribeDemo { + private static string _host = ""; + private static string _groupId = ""; + private static string _clientId = ""; + private static string _topic = ""; + public static void Main(string[] args) { try @@ -64,9 +69,9 @@ namespace TMQExample { // ANCHOR: create_consumer // consumer config - var host = "127.0.0.1"; - var groupId = "group1"; - var clientId = "client1"; + _host = "127.0.0.1"; + _groupId = "group1"; + _clientId = "client1"; var cfg = new Dictionary() { { "td.connect.port", "6030" }, @@ -74,9 +79,9 @@ namespace TMQExample { "msg.with.table.name", "true" }, { "enable.auto.commit", "true" }, { "auto.commit.interval.ms", "1000" }, - { "group.id", groupId }, - { "client.id", clientId }, - { "td.connect.ip", host }, + { "group.id", _groupId }, + { "client.id", _clientId }, + { "td.connect.ip", _host }, { "td.connect.user", "root" }, { "td.connect.pass", "taosdata" }, }; @@ -85,20 +90,32 @@ namespace TMQExample { // create consumer consumer = new ConsumerBuilder>(cfg).Build(); - Console.WriteLine("Create consumer successfully, host: " + host + ", groupId: " + groupId + - ", clientId: " + clientId); + Console.WriteLine( + $"Create consumer successfully, " + + $"host: {_host}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}"); } catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to create native consumer, host: " + host + ", ErrCode:" + e.Code + - ", ErrMessage: " + e.Error); + Console.WriteLine( + $"Failed to create native consumer, " + + $"host: {_host}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}, " + + $"ErrCode: {e.Code}, " + + $"ErrMessage: {e.Error}"); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to create native consumer, host: " + host + ", ErrMessage: " + e.Message); + Console.WriteLine($"Failed to create native consumer, " + + $"host: {_host}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}, " + + $"ErrMessage: {e.Message}"); throw; } @@ -109,11 +126,12 @@ namespace TMQExample static void Consume(IConsumer> consumer) { // ANCHOR: subscribe + _topic = "topic_meters"; try { // subscribe - consumer.Subscribe(new List() { "topic_meters" }); - Console.WriteLine("subscribe topics successfully"); + consumer.Subscribe(new List() { _topic }); + Console.WriteLine("Subscribe topics successfully"); for (int i = 0; i < 50; i++) { // consume message with using block to ensure the result is disposed @@ -133,13 +151,23 @@ namespace TMQExample catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to poll data, ErrCode: " + e.Code + ", ErrMessage: " + e.Error); + Console.WriteLine( + $"Failed to poll data, " + + $"topic: {_topic}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}, " + + $"ErrCode: {e.Code}, " + + $"ErrMessage: {e.Error}"); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to poll data, ErrMessage: " + e.Message); + Console.WriteLine($"Failed to poll data, " + + $"topic: {_topic}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}, " + + $"ErrMessage: {e.Message}"); throw; } // ANCHOR_END: subscribe @@ -152,7 +180,7 @@ namespace TMQExample { // get assignment var assignment = consumer.Assignment; - Console.WriteLine($"now assignment: {assignment}"); + Console.WriteLine($"Now assignment: {assignment}"); // seek to the beginning foreach (var topicPartition in assignment) { @@ -163,13 +191,25 @@ namespace TMQExample catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to execute seek example, ErrCode: " + e.Code + ", ErrMessage: " + e.Error); + Console.WriteLine( + $"Failed to execute seek example, " + + $"topic: {_topic}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}, " + + $"offset: 0, " + + $"ErrCode: {e.Code}, " + + $"ErrMessage: {e.Error}"); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to execute seek example, ErrMessage: " + e.Message); + Console.WriteLine($"Failed to execute seek example, " + + $"topic: {_topic}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}, " + + $"offset: 0, " + + $"ErrMessage: {e.Message}"); throw; } // ANCHOR_END: seek @@ -180,6 +220,7 @@ namespace TMQExample // ANCHOR: commit_offset for (int i = 0; i < 5; i++) { + TopicPartitionOffset topicPartitionOffset = null; try { // consume message with using block to ensure the result is disposed @@ -187,9 +228,10 @@ namespace TMQExample { if (cr == null) continue; // commit offset + topicPartitionOffset = cr.TopicPartitionOffset; consumer.Commit(new List { - cr.TopicPartitionOffset, + topicPartitionOffset, }); Console.WriteLine("Commit offset manually successfully."); } @@ -197,13 +239,26 @@ namespace TMQExample catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to execute commit example, ErrCode:" + e.Code + ", ErrMessage: " + e.Error); + Console.WriteLine( + $"Failed to execute commit example, " + + $"topic: {_topic}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}, " + + $"offset: {topicPartitionOffset}, " + + $"ErrCode: {e.Code}, " + + $"ErrMessage: {e.Error}"); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to execute commit example, ErrMessage: " + e.Message); + Console.WriteLine( + $"Failed to execute commit example, " + + $"topic: {_topic}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}, " + + $"offset: {topicPartitionOffset}, " + + $"ErrMessage: {e.Message}"); throw; } } @@ -221,13 +276,24 @@ namespace TMQExample catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to unsubscribe consumer, ErrCode: " + e.Code + ", ErrMessage: " + e.Error); + Console.WriteLine( + $"Failed to unsubscribe consumer, " + + $"topic: {_topic}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}, " + + $"ErrCode: {e.Code}, " + + $"ErrMessage: {e.Error}"); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to unsubscribe consumer, ErrMessage: " + e.Message); + Console.WriteLine( + $"Failed to execute commit example, " + + $"topic: {_topic}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}, " + + $"ErrMessage: {e.Message}"); throw; } finally @@ -239,4 +305,4 @@ namespace TMQExample // ANCHOR_END: close } } -} +} \ No newline at end of file diff --git a/docs/examples/csharp/wsInsert/Program.cs b/docs/examples/csharp/wsInsert/Program.cs index 36b884a522..9bc47d97f1 100644 --- a/docs/examples/csharp/wsInsert/Program.cs +++ b/docs/examples/csharp/wsInsert/Program.cs @@ -16,10 +16,10 @@ namespace Examples var builder = new ConnectionStringBuilder(connectionString); using (var client = DbDriver.Open(builder)) { - CreateDatabaseAndTable(client,connectionString); - InsertData(client,connectionString); - QueryData(client,connectionString); - QueryWithReqId(client,connectionString); + CreateDatabaseAndTable(client, connectionString); + InsertData(client, connectionString); + QueryData(client, connectionString); + QueryWithReqId(client, connectionString); } } catch (TDengineError e) @@ -52,7 +52,8 @@ namespace Examples catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to create database power or stable meters, ErrCode: " + e.Code + ", ErrMessage: " + e.Error); + Console.WriteLine("Failed to create database power or stable meters, ErrCode: " + e.Code + + ", ErrMessage: " + e.Error); throw; } catch (Exception e) @@ -64,40 +65,43 @@ namespace Examples // ANCHOR_END: create_db_and_table } - private static void InsertData(ITDengineClient client,string connectionString) + private static void InsertData(ITDengineClient client, string connectionString) { // ANCHOR: insert_data + // insert data, please make sure the database and table are created before + var insertQuery = "INSERT INTO " + + "power.d1001 USING power.meters TAGS(2,'California.SanFrancisco') " + + "VALUES " + + "(NOW + 1a, 10.30000, 219, 0.31000) " + + "(NOW + 2a, 12.60000, 218, 0.33000) " + + "(NOW + 3a, 12.30000, 221, 0.31000) " + + "power.d1002 USING power.meters TAGS(3, 'California.SanFrancisco') " + + "VALUES " + + "(NOW + 1a, 10.30000, 218, 0.25000) "; try { - // insert data, please make sure the database and table are created before - var insertQuery = "INSERT INTO " + - "power.d1001 USING power.meters TAGS(2,'California.SanFrancisco') " + - "VALUES " + - "(NOW + 1a, 10.30000, 219, 0.31000) " + - "(NOW + 2a, 12.60000, 218, 0.33000) " + - "(NOW + 3a, 12.30000, 221, 0.31000) " + - "power.d1002 USING power.meters TAGS(3, 'California.SanFrancisco') " + - "VALUES " + - "(NOW + 1a, 10.30000, 218, 0.25000) "; var affectedRows = client.Exec(insertQuery); Console.WriteLine("Successfully inserted " + affectedRows + " rows to power.meters."); } catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to insert data to power.meters, ErrCode: " + e.Code + ", ErrMessage: " + e.Error); + Console.WriteLine("Failed to insert data to power.meters, sql: " + insertQuery + ", ErrCode: " + + e.Code + ", ErrMessage: " + + e.Error); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to insert data to power.meters, ErrMessage: " + e.Message); + Console.WriteLine("Failed to insert data to power.meters, sql: " + insertQuery + ", ErrMessage: " + + e.Message); throw; } // ANCHOR_END: insert_data } - private static void QueryData(ITDengineClient client,string connectionString) + private static void QueryData(ITDengineClient client, string connectionString) { // ANCHOR: select_data // query data, make sure the database and table are created before @@ -108,6 +112,7 @@ namespace Examples { while (rows.Read()) { + // Add your data processing logic here var ts = (DateTime)rows.GetValue(0); var current = (float)rows.GetValue(1); var location = Encoding.UTF8.GetString((byte[])rows.GetValue(2)); @@ -119,28 +124,30 @@ namespace Examples catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to query data from power.meters, sql: " + query + ", ErrCode: " + e.Code + ", ErrMessage: " + e.Error); + Console.WriteLine("Failed to query data from power.meters, sql: " + query + ", ErrCode: " + e.Code + + ", ErrMessage: " + e.Error); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to query data from power.meters, sql: " + query + ", ErrMessage: " + e.Message); + Console.WriteLine( + "Failed to query data from power.meters, sql: " + query + ", ErrMessage: " + e.Message); throw; } // ANCHOR_END: select_data } - private static void QueryWithReqId(ITDengineClient client,string connectionString) + private static void QueryWithReqId(ITDengineClient client, string connectionString) { // ANCHOR: query_id var reqId = (long)3; + // query data + var query = "SELECT ts, current, location FROM power.meters limit 1"; try { - // query data - var query = "SELECT ts, current, location FROM power.meters limit 1"; // query with request id 3 - using (var rows = client.Query(query,reqId)) + using (var rows = client.Query(query, reqId)) { while (rows.Read()) { @@ -155,16 +162,18 @@ namespace Examples catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to execute sql with reqId: " + reqId + ", ErrCode: " + e.Code + ", ErrMessage: " + e.Error); + Console.WriteLine("Failed to execute sql with reqId: " + reqId + ", sql: " + query + ", ErrCode: " + + e.Code + ", ErrMessage: " + e.Error); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to execute sql with reqId: " + reqId + ", ErrMessage: " + e.Message); + Console.WriteLine("Failed to execute sql with reqId: " + reqId + ", sql: " + query + ", ErrMessage: " + + e.Message); throw; } // ANCHOR_END: query_id } } -} +} \ No newline at end of file diff --git a/docs/examples/csharp/wssubscribe/Program.cs b/docs/examples/csharp/wssubscribe/Program.cs index 21abe10847..5f5afc575a 100644 --- a/docs/examples/csharp/wssubscribe/Program.cs +++ b/docs/examples/csharp/wssubscribe/Program.cs @@ -6,6 +6,11 @@ namespace TMQExample { internal class SubscribeDemo { + private static string _host = ""; + private static string _groupId = ""; + private static string _clientId = ""; + private static string _topic = ""; + public static void Main(string[] args) { try @@ -68,9 +73,9 @@ namespace TMQExample { // ANCHOR: create_consumer // consumer config - var host = "127.0.0.1"; - var groupId = "group1"; - var clientId = "client1"; + _host = "127.0.0.1"; + _groupId = "group1"; + _clientId = "client1"; var cfg = new Dictionary() { { "td.connect.type", "WebSocket" }, @@ -79,9 +84,9 @@ namespace TMQExample { "msg.with.table.name", "true" }, { "enable.auto.commit", "true" }, { "auto.commit.interval.ms", "1000" }, - { "group.id", groupId }, - { "client.id", clientId }, - { "td.connect.ip", host }, + { "group.id", _groupId }, + { "client.id", _clientId }, + { "td.connect.ip", _host }, { "td.connect.user", "root" }, { "td.connect.pass", "taosdata" }, }; @@ -90,20 +95,32 @@ namespace TMQExample { // create consumer consumer = new ConsumerBuilder>(cfg).Build(); - Console.WriteLine("Create consumer successfully, host: " + host + ", groupId: " + groupId + - ", clientId: " + clientId); + Console.WriteLine( + $"Create consumer successfully, " + + $"host: {_host}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}"); } catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to create websocket consumer, host: " + host + ", ErrCode: " + e.Code + - ", ErrMessage: " + e.Error); + Console.WriteLine( + $"Failed to create native consumer, " + + $"host: {_host}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}, " + + $"ErrCode: {e.Code}, " + + $"ErrMessage: {e.Error}"); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to create websocket consumer, host: " + host + ", ErrMessage: " + e.Message); + Console.WriteLine($"Failed to create native consumer, " + + $"host: {_host}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}, " + + $"ErrMessage: {e.Message}"); throw; } @@ -114,10 +131,11 @@ namespace TMQExample static void Consume(IConsumer> consumer) { // ANCHOR: subscribe + _topic = "topic_meters"; try { // subscribe - consumer.Subscribe(new List() { "topic_meters" }); + consumer.Subscribe(new List() { _topic }); Console.WriteLine("Subscribe topics successfully"); for (int i = 0; i < 50; i++) { @@ -138,13 +156,23 @@ namespace TMQExample catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to poll data, ErrCode: " + e.Code + ", ErrMessage: " + e.Error); + Console.WriteLine( + $"Failed to poll data, " + + $"topic: {_topic}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}, " + + $"ErrCode: {e.Code}, " + + $"ErrMessage: {e.Error}"); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to poll data, ErrMessage: " + e.Message); + Console.WriteLine($"Failed to poll data, " + + $"topic: {_topic}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}, " + + $"ErrMessage: {e.Message}"); throw; } // ANCHOR_END: subscribe @@ -168,13 +196,25 @@ namespace TMQExample catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to execute seek example, ErrCode: " + e.Code + ", ErrMessage: " + e.Error); + Console.WriteLine( + $"Failed to execute seek example, " + + $"topic: {_topic}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}, " + + $"offset: 0, " + + $"ErrCode: {e.Code}, " + + $"ErrMessage: {e.Error}"); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to execute seek example, ErrMessage: " + e.Message); + Console.WriteLine($"Failed to execute seek example, " + + $"topic: {_topic}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}, " + + $"offset: 0, " + + $"ErrMessage: {e.Message}"); throw; } // ANCHOR_END: seek @@ -185,6 +225,7 @@ namespace TMQExample // ANCHOR: commit_offset for (int i = 0; i < 5; i++) { + TopicPartitionOffset topicPartitionOffset = null; try { // consume message with using block to ensure the result is disposed @@ -192,9 +233,10 @@ namespace TMQExample { if (cr == null) continue; // commit offset + topicPartitionOffset = cr.TopicPartitionOffset; consumer.Commit(new List { - cr.TopicPartitionOffset, + topicPartitionOffset, }); Console.WriteLine("Commit offset manually successfully."); } @@ -202,13 +244,26 @@ namespace TMQExample catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to execute commit example, ErrCode: " + e.Code + ", ErrMessage: " + e.Error); + Console.WriteLine( + $"Failed to execute commit example, " + + $"topic: {_topic}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}, " + + $"offset: {topicPartitionOffset}, " + + $"ErrCode: {e.Code}, " + + $"ErrMessage: {e.Error}"); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to execute commit example, ErrMessage: " + e.Message); + Console.WriteLine( + $"Failed to execute commit example, " + + $"topic: {_topic}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}, " + + $"offset: {topicPartitionOffset}, " + + $"ErrMessage: {e.Message}"); throw; } } @@ -226,13 +281,24 @@ namespace TMQExample catch (TDengineError e) { // handle TDengine error - Console.WriteLine("Failed to unsubscribe consumer, ErrCode :" + e.Code + ", ErrMessage: " + e.Error); + Console.WriteLine( + $"Failed to unsubscribe consumer, " + + $"topic: {_topic}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}, " + + $"ErrCode: {e.Code}, " + + $"ErrMessage: {e.Error}"); throw; } catch (Exception e) { // handle other exceptions - Console.WriteLine("Failed to unsubscribe consumer, ErrMessage: " + e.Message); + Console.WriteLine( + $"Failed to execute commit example, " + + $"topic: {_topic}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}, " + + $"ErrMessage: {e.Message}"); throw; } finally @@ -244,4 +310,4 @@ namespace TMQExample // ANCHOR_END: close } } -} +} \ No newline at end of file diff --git a/docs/examples/go/queryreqid/main.go b/docs/examples/go/queryreqid/main.go index 39d1d6bd5e..0763feceff 100644 --- a/docs/examples/go/queryreqid/main.go +++ b/docs/examples/go/queryreqid/main.go @@ -1,58 +1,60 @@ -package main - -import ( - "context" - "database/sql" - "fmt" - "log" - "time" - - _ "github.com/taosdata/driver-go/v3/taosSql" -) - -func main() { - taosDSN := "root:taosdata@tcp(localhost:6030)/" - db, err := sql.Open("taosSql", taosDSN) - if err != nil { - log.Fatalln("Failed to connect to " + taosDSN + "; ErrMessage: " + err.Error()) - } - defer db.Close() - initEnv(db) - // ANCHOR: query_id - // use context to set request id - reqId := int64(3) - ctx := context.WithValue(context.Background(), "taos_req_id", reqId) - // execute query with context - rows, err := db.QueryContext(ctx, "SELECT ts, current, location FROM power.meters limit 1") - if err != nil { - log.Fatalf("Failed to execute sql with reqId: %d, url: %s; ErrMessage: %s\n", reqId, taosDSN, err.Error()) - } - for rows.Next() { - var ( - ts time.Time - current float32 - location string - ) - err = rows.Scan(&ts, ¤t, &location) - if err != nil { - log.Fatal("Scan error: ", err) - } - fmt.Printf("ts: %s, current: %f, location: %s\n", ts, current, location) - } - // ANCHOR_END: query_id -} - -func initEnv(conn *sql.DB) { - _, err := conn.Exec("CREATE DATABASE IF NOT EXISTS power") - if err != nil { - log.Fatal("Create database power error: ", err) - } - _, err = conn.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))") - if err != nil { - log.Fatal("Create stable meters error: ", err) - } - _, err = conn.Exec("INSERT INTO power.d1001 USING power.meters TAGS (2, 'California.SanFrancisco') VALUES (NOW , 10.2, 219, 0.32)") - if err != nil { - log.Fatal("Insert data to power.meters error: ", err) - } -} +package main + +import ( + "context" + "database/sql" + "fmt" + "log" + "time" + + _ "github.com/taosdata/driver-go/v3/taosSql" +) + +func main() { + taosDSN := "root:taosdata@tcp(localhost:6030)/" + db, err := sql.Open("taosSql", taosDSN) + if err != nil { + log.Fatalln("Failed to connect to " + taosDSN + ", ErrMessage: " + err.Error()) + } + defer db.Close() + initEnv(db) + // ANCHOR: query_id + // use context to set request id + reqId := int64(3) + ctx := context.WithValue(context.Background(), "taos_req_id", reqId) + // execute query with context + querySql := "SELECT ts, current, location FROM power.meters limit 1" + rows, err := db.QueryContext(ctx, querySql) + if err != nil { + log.Fatalf("Failed to execute sql with reqId: %d, url: %s, sql: %s, ErrMessage: %s\n", reqId, taosDSN, querySql, err.Error()) + } + for rows.Next() { + // Add your data processing logic here + var ( + ts time.Time + current float32 + location string + ) + err = rows.Scan(&ts, ¤t, &location) + if err != nil { + log.Fatalf("Failed to scan data, reqId: %d, url:%s, sql: %s, ErrMessage: %s\n", reqId, taosDSN, querySql, err) + } + fmt.Printf("ts: %s, current: %f, location: %s\n", ts, current, location) + } + // ANCHOR_END: query_id +} + +func initEnv(conn *sql.DB) { + _, err := conn.Exec("CREATE DATABASE IF NOT EXISTS power") + if err != nil { + log.Fatal("Create database power error: ", err) + } + _, err = conn.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))") + if err != nil { + log.Fatal("Create stable meters error: ", err) + } + _, err = conn.Exec("INSERT INTO power.d1001 USING power.meters TAGS (2, 'California.SanFrancisco') VALUES (NOW , 10.2, 219, 0.32)") + if err != nil { + log.Fatal("Insert data to power.meters error: ", err) + } +} diff --git a/docs/examples/go/sqlquery/main.go b/docs/examples/go/sqlquery/main.go index f0e0f1c97e..1bfb74ca87 100644 --- a/docs/examples/go/sqlquery/main.go +++ b/docs/examples/go/sqlquery/main.go @@ -1,86 +1,86 @@ -package main - -import ( - "database/sql" - "fmt" - "log" - "time" - - _ "github.com/taosdata/driver-go/v3/taosSql" -) - -func main() { - var taosDSN = "root:taosdata@tcp(localhost:6030)/" - db, err := sql.Open("taosSql", taosDSN) - if err != nil { - log.Fatalln("Failed to connect to " + taosDSN + ", ErrMessage: " + err.Error()) - } - defer db.Close() - // ANCHOR: create_db_and_table - // create database - res, err := db.Exec("CREATE DATABASE IF NOT EXISTS power") - if err != nil { - log.Fatalln("Failed to create database power, ErrMessage: " + err.Error()) - } - rowsAffected, err := res.RowsAffected() - if err != nil { - log.Fatalln("Failed to get create database rowsAffected, ErrMessage: " + err.Error()) - } - // you can check rowsAffected here - fmt.Println("Create database power successfully, rowsAffected: ", rowsAffected) - // create table - res, err = db.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))") - if err != nil { - log.Fatalln("Failed to create stable meters, ErrMessage: " + err.Error()) - } - rowsAffected, err = res.RowsAffected() - if err != nil { - log.Fatalln("Failed to get create stable rowsAffected, ErrMessage: " + err.Error()) - } - // you can check rowsAffected here - fmt.Println("Create stable power.meters successfully, rowsAffected:", rowsAffected) - // ANCHOR_END: create_db_and_table - // ANCHOR: insert_data - // insert data, please make sure the database and table are created before - insertQuery := "INSERT INTO " + - "power.d1001 USING power.meters TAGS(2,'California.SanFrancisco') " + - "VALUES " + - "(NOW + 1a, 10.30000, 219, 0.31000) " + - "(NOW + 2a, 12.60000, 218, 0.33000) " + - "(NOW + 3a, 12.30000, 221, 0.31000) " + - "power.d1002 USING power.meters TAGS(3, 'California.SanFrancisco') " + - "VALUES " + - "(NOW + 1a, 10.30000, 218, 0.25000) " - res, err = db.Exec(insertQuery) - if err != nil { - log.Fatal("Failed to insert data to power.meters, ErrMessage: " + err.Error()) - } - rowsAffected, err = res.RowsAffected() - if err != nil { - log.Fatal("Failed to get insert rowsAffected, ErrMessage: " + err.Error()) - } - // you can check affectedRows here - fmt.Printf("Successfully inserted %d rows to power.meters.\n", rowsAffected) - // ANCHOR_END: insert_data - // ANCHOR: select_data - // query data, make sure the database and table are created before - sql := "SELECT ts, current, location FROM power.meters limit 100" - rows, err := db.Query(sql) - if err != nil { - log.Fatal("Failed to query data from power.meters, ErrMessage: " + err.Error()) - } - for rows.Next() { - var ( - ts time.Time - current float32 - location string - ) - err = rows.Scan(&ts, ¤t, &location) - if err != nil { - log.Fatal("Failed to scan data, sql:" + sql + ", ErrMessage: " + err.Error()) - } - // you can check data here - fmt.Printf("ts: %s, current: %f, location: %s\n", ts, current, location) - } - // ANCHOR_END: select_data -} +package main + +import ( + "database/sql" + "fmt" + "log" + "time" + + _ "github.com/taosdata/driver-go/v3/taosSql" +) + +func main() { + var taosDSN = "root:taosdata@tcp(localhost:6030)/" + db, err := sql.Open("taosSql", taosDSN) + if err != nil { + log.Fatalln("Failed to connect to " + taosDSN + ", ErrMessage: " + err.Error()) + } + defer db.Close() + // ANCHOR: create_db_and_table + // create database + res, err := db.Exec("CREATE DATABASE IF NOT EXISTS power") + if err != nil { + log.Fatalln("Failed to create database power, ErrMessage: " + err.Error()) + } + rowsAffected, err := res.RowsAffected() + if err != nil { + log.Fatalln("Failed to get create database rowsAffected, ErrMessage: " + err.Error()) + } + // you can check rowsAffected here + fmt.Println("Create database power successfully, rowsAffected: ", rowsAffected) + // create table + res, err = db.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))") + if err != nil { + log.Fatalln("Failed to create stable meters, ErrMessage: " + err.Error()) + } + rowsAffected, err = res.RowsAffected() + if err != nil { + log.Fatalln("Failed to get create stable rowsAffected, ErrMessage: " + err.Error()) + } + // you can check rowsAffected here + fmt.Println("Create stable power.meters successfully, rowsAffected:", rowsAffected) + // ANCHOR_END: create_db_and_table + // ANCHOR: insert_data + // insert data, please make sure the database and table are created before + insertQuery := "INSERT INTO " + + "power.d1001 USING power.meters TAGS(2,'California.SanFrancisco') " + + "VALUES " + + "(NOW + 1a, 10.30000, 219, 0.31000) " + + "(NOW + 2a, 12.60000, 218, 0.33000) " + + "(NOW + 3a, 12.30000, 221, 0.31000) " + + "power.d1002 USING power.meters TAGS(3, 'California.SanFrancisco') " + + "VALUES " + + "(NOW + 1a, 10.30000, 218, 0.25000) " + res, err = db.Exec(insertQuery) + if err != nil { + log.Fatalf("Failed to insert data to power.meters, sql: %s, ErrMessage: %s\n", insertQuery, err.Error()) + } + rowsAffected, err = res.RowsAffected() + if err != nil { + log.Fatalf("Failed to get insert rowsAffected, sql: %s, ErrMessage: %s\n", insertQuery, err.Error()) + } + // you can check affectedRows here + fmt.Printf("Successfully inserted %d rows to power.meters.\n", rowsAffected) + // ANCHOR_END: insert_data + // ANCHOR: select_data + // query data, make sure the database and table are created before + sql := "SELECT ts, current, location FROM power.meters limit 100" + rows, err := db.Query(sql) + if err != nil { + log.Fatalf("Failed to query data from power.meters, sql: %s, ErrMessage: %s\n", sql, err.Error()) + } + for rows.Next() { + // Add your data processing logic here + var ( + ts time.Time + current float32 + location string + ) + err = rows.Scan(&ts, ¤t, &location) + if err != nil { + log.Fatalf("Failed to scan data, sql: %s, ErrMessage: %s\n", sql, err) + } + fmt.Printf("ts: %s, current: %f, location: %s\n", ts, current, location) + } + // ANCHOR_END: select_data +} diff --git a/docs/examples/go/tmq/native/main.go b/docs/examples/go/tmq/native/main.go index 638a07d235..1d4a22b880 100644 --- a/docs/examples/go/tmq/native/main.go +++ b/docs/examples/go/tmq/native/main.go @@ -1,136 +1,179 @@ -package main - -import ( - "database/sql" - "fmt" - "log" - "time" - - "github.com/taosdata/driver-go/v3/af/tmq" - tmqcommon "github.com/taosdata/driver-go/v3/common/tmq" - _ "github.com/taosdata/driver-go/v3/taosSql" -) - -var done = make(chan struct{}) - -func main() { - // init env - taosDSN := "root:taosdata@tcp(127.0.0.1:6030)/" - conn, err := sql.Open("taosSql", taosDSN) - if err != nil { - log.Fatalln("Failed to connect to " + taosDSN + "; ErrMessage: " + err.Error()) - } - defer func() { - conn.Close() - }() - initEnv(conn) - // ANCHOR: create_consumer - // create consumer - groupID := "group1" - clientID := "client1" - host := "127.0.0.1" - consumer, err := tmq.NewConsumer(&tmqcommon.ConfigMap{ - "td.connect.user": "root", - "td.connect.pass": "taosdata", - "auto.offset.reset": "latest", - "msg.with.table.name": "true", - "enable.auto.commit": "true", - "auto.commit.interval.ms": "1000", - "group.id": groupID, - "client.id": clientID, - }) - if err != nil { - log.Fatalln("Failed to create native consumer, host : " + host + "; ErrMessage: " + err.Error()) - } - log.Println("Create consumer successfully, host: " + host + ", groupId: " + groupID + ", clientId: " + clientID) - - // ANCHOR_END: create_consumer - // ANCHOR: subscribe - err = consumer.Subscribe("topic_meters", nil) - if err != nil { - log.Fatalln("Failed to subscribe topic_meters, ErrMessage: " + err.Error()) - } - log.Println("Subscribe topics successfully") - for i := 0; i < 50; i++ { - ev := consumer.Poll(100) - if ev != nil { - switch e := ev.(type) { - case *tmqcommon.DataMessage: - // process your data here - fmt.Printf("data:%v\n", e) - // ANCHOR: commit_offset - // commit offset - _, err = consumer.CommitOffsets([]tmqcommon.TopicPartition{e.TopicPartition}) - if err != nil { - log.Fatalln("Failed to commit offset, ErrMessage: " + err.Error()) - } - log.Println("Commit offset manually successfully.") - // ANCHOR_END: commit_offset - case tmqcommon.Error: - fmt.Printf("%% Error: %v: %v\n", e.Code(), e) - log.Fatalln("Failed to poll data, ErrMessage: " + err.Error()) - } - } - } - // ANCHOR_END: subscribe - // ANCHOR: seek - // get assignment - partitions, err := consumer.Assignment() - if err != nil { - log.Fatal("Failed to get assignment, ErrMessage: " + err.Error()) - } - fmt.Println("Now assignment:", partitions) - for i := 0; i < len(partitions); i++ { - // seek to the beginning - err = consumer.Seek(tmqcommon.TopicPartition{ - Topic: partitions[i].Topic, - Partition: partitions[i].Partition, - Offset: 0, - }, 0) - if err != nil { - log.Fatalln("Failed to execute seek example, ErrMessage: " + err.Error()) - } - } - fmt.Println("Assignment seek to beginning successfully") - // ANCHOR_END: seek - // ANCHOR: close - // unsubscribe - err = consumer.Unsubscribe() - if err != nil { - log.Fatal("Failed to unsubscribe consumer, ErrMessage: " + err.Error()) - } - fmt.Println("Consumer unsubscribed successfully.") - // close consumer - err = consumer.Close() - if err != nil { - log.Fatal("Failed to close consumer, ErrMessage: " + err.Error()) - } - fmt.Println("Consumer closed successfully.") - // ANCHOR_END: close - <-done -} - -func initEnv(conn *sql.DB) { - _, err := conn.Exec("CREATE DATABASE IF NOT EXISTS power") - if err != nil { - log.Fatal("Failed to create database, ErrMessage: " + err.Error()) - } - _, err = conn.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))") - if err != nil { - log.Fatal("Failed to create stable, ErrMessage: " + err.Error()) - } - _, err = conn.Exec("CREATE TOPIC IF NOT EXISTS topic_meters AS SELECT ts, current, voltage, phase, groupid, location FROM power.meters") - if err != nil { - log.Fatal("Failed to create topic, ErrMessage: " + err.Error()) - } - go func() { - for i := 0; i < 10; i++ { - time.Sleep(time.Second) - _, err = conn.Exec("INSERT INTO power.d1001 USING power.meters TAGS (2, 'California.SanFrancisco') VALUES (NOW , 10.2, 219, 0.32)") - if err != nil { - log.Fatal("Failed to insert data, ErrMessage: " + err.Error()) - } - } - done <- struct{}{} - }() -} +package main + +import ( + "database/sql" + "fmt" + "log" + "time" + + "github.com/taosdata/driver-go/v3/af/tmq" + tmqcommon "github.com/taosdata/driver-go/v3/common/tmq" + _ "github.com/taosdata/driver-go/v3/taosSql" +) + +var done = make(chan struct{}) +var groupID string +var clientID string +var host string +var topic string + +func main() { + // init env + taosDSN := "root:taosdata@tcp(127.0.0.1:6030)/" + conn, err := sql.Open("taosSql", taosDSN) + if err != nil { + log.Fatalln("Failed to connect to " + taosDSN + ", ErrMessage: " + err.Error()) + } + defer func() { + conn.Close() + }() + initEnv(conn) + // ANCHOR: create_consumer + // create consumer + groupID = "group1" + clientID = "client1" + host = "127.0.0.1" + consumer, err := tmq.NewConsumer(&tmqcommon.ConfigMap{ + "td.connect.user": "root", + "td.connect.pass": "taosdata", + "auto.offset.reset": "latest", + "msg.with.table.name": "true", + "enable.auto.commit": "true", + "auto.commit.interval.ms": "1000", + "group.id": groupID, + "client.id": clientID, + }) + if err != nil { + log.Fatalf( + "Failed to create native consumer, host: %s, groupId: %s, clientId: %s, ErrMessage: %s\n", + host, + groupID, + clientID, + err.Error(), + ) + } + log.Printf("Create consumer successfully, host: %s, groupId: %s, clientId: %s\n", host, groupID, clientID) + + // ANCHOR_END: create_consumer + // ANCHOR: subscribe + topic = "topic_meters" + err = consumer.Subscribe(topic, nil) + if err != nil { + log.Fatalf( + "Failed to subscribe topic_meters, topic: %s, groupId: %s, clientId: %s, ErrMessage: %s\n", + topic, + groupID, + clientID, + err.Error(), + ) + } + log.Println("Subscribe topics successfully") + for i := 0; i < 50; i++ { + ev := consumer.Poll(100) + if ev != nil { + switch e := ev.(type) { + case *tmqcommon.DataMessage: + // process your data here + fmt.Printf("data:%v\n", e) + // ANCHOR: commit_offset + // commit offset + _, err = consumer.CommitOffsets([]tmqcommon.TopicPartition{e.TopicPartition}) + if err != nil { + log.Fatalf( + "Failed to commit offset, topic: %s, groupId: %s, clientId: %s, offset %s, ErrMessage: %s\n", + topic, + groupID, + clientID, + e.TopicPartition, + err.Error(), + ) + } + log.Println("Commit offset manually successfully.") + // ANCHOR_END: commit_offset + case tmqcommon.Error: + log.Fatalf("Failed to poll data, topic: %s, groupId: %s, clientId: %s, ErrMessage: %s\n", topic, groupID, clientID, e.Error()) + } + } + } + // ANCHOR_END: subscribe + // ANCHOR: seek + // get assignment + partitions, err := consumer.Assignment() + if err != nil { + log.Fatalf("Failed to get assignment, topic: %s, groupId: %s, clientId: %s, ErrMessage: %s\n", topic, groupID, clientID, err.Error()) + } + fmt.Println("Now assignment:", partitions) + for i := 0; i < len(partitions); i++ { + // seek to the beginning + err = consumer.Seek(tmqcommon.TopicPartition{ + Topic: partitions[i].Topic, + Partition: partitions[i].Partition, + Offset: 0, + }, 0) + if err != nil { + log.Fatalf( + "Failed to execute seek example, topic: %s, groupId: %s, clientId: %s, partition: %d, offset: %d, ErrMessage: %s\n", + topic, + groupID, + clientID, + partitions[i].Partition, + 0, + err.Error(), + ) + } + } + fmt.Println("Assignment seek to beginning successfully") + // ANCHOR_END: seek + // ANCHOR: close + // unsubscribe + err = consumer.Unsubscribe() + if err != nil { + log.Fatalf( + "Failed to unsubscribe consumer, topic: %s, groupId: %s, clientId: %s, ErrMessage: %s\n", + topic, + groupID, + clientID, + err.Error(), + ) + } + fmt.Println("Consumer unsubscribed successfully.") + // close consumer + err = consumer.Close() + if err != nil { + log.Fatalf( + "Failed to close consumer, topic: %s, groupId: %s, clientId: %s, ErrMessage: %s\n", + topic, + groupID, + clientID, + err.Error(), + ) + } + fmt.Println("Consumer closed successfully.") + // ANCHOR_END: close + <-done +} + +func initEnv(conn *sql.DB) { + _, err := conn.Exec("CREATE DATABASE IF NOT EXISTS power") + if err != nil { + log.Fatal("Failed to create database, ErrMessage: " + err.Error()) + } + _, err = conn.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))") + if err != nil { + log.Fatal("Failed to create stable, ErrMessage: " + err.Error()) + } + _, err = conn.Exec("CREATE TOPIC IF NOT EXISTS topic_meters AS SELECT ts, current, voltage, phase, groupid, location FROM power.meters") + if err != nil { + log.Fatal("Failed to create topic, ErrMessage: " + err.Error()) + } + go func() { + for i := 0; i < 10; i++ { + time.Sleep(time.Second) + _, err = conn.Exec("INSERT INTO power.d1001 USING power.meters TAGS (2, 'California.SanFrancisco') VALUES (NOW , 10.2, 219, 0.32)") + if err != nil { + log.Fatal("Failed to insert data, ErrMessage: " + err.Error()) + } + } + done <- struct{}{} + }() +} diff --git a/docs/examples/go/tmq/ws/main.go b/docs/examples/go/tmq/ws/main.go index 70ea3af0b3..aaed8395e0 100644 --- a/docs/examples/go/tmq/ws/main.go +++ b/docs/examples/go/tmq/ws/main.go @@ -1,141 +1,197 @@ -package main - -import ( - "database/sql" - "fmt" - "log" - "time" - - "github.com/taosdata/driver-go/v3/common" - tmqcommon "github.com/taosdata/driver-go/v3/common/tmq" - _ "github.com/taosdata/driver-go/v3/taosWS" - "github.com/taosdata/driver-go/v3/ws/tmq" -) - -var done = make(chan struct{}) - -func main() { - // init env - taosDSN := "root:taosdata@ws(127.0.0.1:6041)/" - conn, err := sql.Open("taosWS", taosDSN) - if err != nil { - log.Fatalln("Failed to connect to " + taosDSN + "; ErrMessage: " + err.Error()) - } - defer func() { - conn.Close() - }() - initEnv(conn) - // ANCHOR: create_consumer - // create consumer - wsUrl := "ws://127.0.0.1:6041" - groupID := "group1" - clientID := "client1" - consumer, err := tmq.NewConsumer(&tmqcommon.ConfigMap{ - "ws.url": wsUrl, - "ws.message.channelLen": uint(0), - "ws.message.timeout": common.DefaultMessageTimeout, - "ws.message.writeWait": common.DefaultWriteWait, - "td.connect.user": "root", - "td.connect.pass": "taosdata", - "auto.offset.reset": "latest", - "msg.with.table.name": "true", - "enable.auto.commit": "true", - "auto.commit.interval.ms": "1000", - "group.id": groupID, - "client.id": clientID, - }) - if err != nil { - log.Fatalln("Failed to create websocket consumer, host : " + wsUrl + "; ErrMessage: " + err.Error()) - } - log.Println("Create consumer successfully, host: " + wsUrl + ", groupId: " + groupID + ", clientId: " + clientID) - - // ANCHOR_END: create_consumer - // ANCHOR: subscribe - err = consumer.Subscribe("topic_meters", nil) - if err != nil { - log.Fatalln("Failed to subscribe topic_meters, ErrMessage: " + err.Error()) - } - log.Println("Subscribe topics successfully") - for i := 0; i < 50; i++ { - ev := consumer.Poll(100) - if ev != nil { - switch e := ev.(type) { - case *tmqcommon.DataMessage: - // process your data here - fmt.Printf("data:%v\n", e) - // ANCHOR: commit_offset - // commit offset - _, err = consumer.CommitOffsets([]tmqcommon.TopicPartition{e.TopicPartition}) - if err != nil { - log.Fatalln("Failed to commit offset, ErrMessage: " + err.Error()) - } - log.Println("Commit offset manually successfully.") - // ANCHOR_END: commit_offset - case tmqcommon.Error: - fmt.Printf("%% Error: %v: %v\n", e.Code(), e) - log.Fatalln("Failed to poll data, ErrMessage: " + err.Error()) - } - } - } - // ANCHOR_END: subscribe - // ANCHOR: seek - // get assignment - partitions, err := consumer.Assignment() - if err != nil { - log.Fatal("Failed to get assignment, ErrMessage: " + err.Error()) - } - fmt.Println("Now assignment:", partitions) - for i := 0; i < len(partitions); i++ { - // seek to the beginning - err = consumer.Seek(tmqcommon.TopicPartition{ - Topic: partitions[i].Topic, - Partition: partitions[i].Partition, - Offset: 0, - }, 0) - if err != nil { - log.Fatalln("Failed to execute seek example, ErrMessage: " + err.Error()) - } - } - fmt.Println("Assignment seek to beginning successfully") - // ANCHOR_END: seek - // ANCHOR: close - // unsubscribe - err = consumer.Unsubscribe() - if err != nil { - log.Fatal("Failed to unsubscribe consumer, ErrMessage: " + err.Error()) - } - fmt.Println("Consumer unsubscribed successfully.") - // close consumer - err = consumer.Close() - if err != nil { - log.Fatal("Failed to close consumer, ErrMessage: " + err.Error()) - } - fmt.Println("Consumer closed successfully.") - // ANCHOR_END: close - <-done -} - -func initEnv(conn *sql.DB) { - _, err := conn.Exec("CREATE DATABASE IF NOT EXISTS power") - if err != nil { - log.Fatal("Failed to create database, ErrMessage: " + err.Error()) - } - _, err = conn.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))") - if err != nil { - log.Fatal("Failed to create stable, ErrMessage: " + err.Error()) - } - _, err = conn.Exec("CREATE TOPIC IF NOT EXISTS topic_meters AS SELECT ts, current, voltage, phase, groupid, location FROM power.meters") - if err != nil { - log.Fatal("Failed to create topic, ErrMessage: " + err.Error()) - } - go func() { - for i := 0; i < 10; i++ { - time.Sleep(time.Second) - _, err = conn.Exec("INSERT INTO power.d1001 USING power.meters TAGS (2, 'California.SanFrancisco') VALUES (NOW , 10.2, 219, 0.32)") - if err != nil { - log.Fatal("Failed to insert data, ErrMessage: " + err.Error()) - } - } - done <- struct{}{} - }() -} +package main + +import ( + "database/sql" + "fmt" + "log" + "time" + + "github.com/taosdata/driver-go/v3/common" + tmqcommon "github.com/taosdata/driver-go/v3/common/tmq" + _ "github.com/taosdata/driver-go/v3/taosWS" + "github.com/taosdata/driver-go/v3/ws/tmq" +) + +var done = make(chan struct{}) +var groupID string +var clientID string +var host string +var topic string + +func main() { + // init env + taosDSN := "root:taosdata@ws(127.0.0.1:6041)/" + conn, err := sql.Open("taosWS", taosDSN) + if err != nil { + log.Fatalln("Failed to connect to " + taosDSN + ", ErrMessage: " + err.Error()) + } + defer func() { + conn.Close() + }() + initEnv(conn) + // ANCHOR: create_consumer + // create consumer + wsUrl := "ws://127.0.0.1:6041" + groupID = "group1" + clientID = "client1" + host = "127.0.0.1" + consumer, err := tmq.NewConsumer(&tmqcommon.ConfigMap{ + "ws.url": wsUrl, + "ws.message.channelLen": uint(0), + "ws.message.timeout": common.DefaultMessageTimeout, + "ws.message.writeWait": common.DefaultWriteWait, + "td.connect.user": "root", + "td.connect.pass": "taosdata", + "auto.offset.reset": "latest", + "msg.with.table.name": "true", + "enable.auto.commit": "true", + "auto.commit.interval.ms": "1000", + "group.id": groupID, + "client.id": clientID, + }) + if err != nil { + log.Fatalf( + "Failed to create websocket consumer, host: %s, groupId: %s, clientId: %s, ErrMessage: %s\n", + host, + groupID, + clientID, + err.Error(), + ) + } + log.Printf("Create consumer successfully, host: %s, groupId: %s, clientId: %s\n", host, groupID, clientID) + + // ANCHOR_END: create_consumer + // ANCHOR: subscribe + topic = "topic_meters" + err = consumer.Subscribe(topic, nil) + if err != nil { + log.Fatalf( + "Failed to subscribe topic_meters, topic: %s, groupId: %s, clientId: %s, ErrMessage: %s\n", + topic, + groupID, + clientID, + err.Error(), + ) + } + log.Println("Subscribe topics successfully") + for i := 0; i < 50; i++ { + ev := consumer.Poll(100) + if ev != nil { + switch e := ev.(type) { + case *tmqcommon.DataMessage: + // process your data here + fmt.Printf("data:%v\n", e) + // ANCHOR: commit_offset + // commit offset + _, err = consumer.CommitOffsets([]tmqcommon.TopicPartition{e.TopicPartition}) + if err != nil { + log.Fatalf( + "Failed to commit offset, topic: %s, groupId: %s, clientId: %s, offset %s, ErrMessage: %s\n", + topic, + groupID, + clientID, + e.TopicPartition, + err.Error(), + ) + } + log.Println("Commit offset manually successfully.") + // ANCHOR_END: commit_offset + case tmqcommon.Error: + log.Fatalf( + "Failed to poll data, topic: %s, groupId: %s, clientId: %s, ErrMessage: %s\n", + topic, + groupID, + clientID, + e.Error(), + ) + } + } + } + // ANCHOR_END: subscribe + // ANCHOR: seek + // get assignment + partitions, err := consumer.Assignment() + if err != nil { + log.Fatalf( + "Failed to get assignment, topic: %s, groupId: %s, clientId: %s, ErrMessage: %s\n", + topic, + groupID, + clientID, + err.Error(), + ) + } + fmt.Println("Now assignment:", partitions) + for i := 0; i < len(partitions); i++ { + // seek to the beginning + err = consumer.Seek(tmqcommon.TopicPartition{ + Topic: partitions[i].Topic, + Partition: partitions[i].Partition, + Offset: 0, + }, 0) + if err != nil { + log.Fatalf( + "Failed to execute seek example, topic: %s, groupId: %s, clientId: %s, partition: %d, offset: %d, ErrMessage: %s\n", + topic, + groupID, + clientID, + partitions[i].Partition, + 0, + err.Error(), + ) + } + } + fmt.Println("Assignment seek to beginning successfully") + // ANCHOR_END: seek + // ANCHOR: close + // unsubscribe + err = consumer.Unsubscribe() + if err != nil { + log.Fatalf( + "Failed to unsubscribe consumer, topic: %s, groupId: %s, clientId: %s, ErrMessage: %s\n", + topic, + groupID, + clientID, + err.Error(), + ) + } + fmt.Println("Consumer unsubscribed successfully.") + // close consumer + err = consumer.Close() + if err != nil { + log.Fatalf( + "Failed to close consumer, topic: %s, groupId: %s, clientId: %s, ErrMessage: %s\n", + topic, + groupID, + clientID, + err.Error(), + ) + } + fmt.Println("Consumer closed successfully.") + // ANCHOR_END: close + <-done +} + +func initEnv(conn *sql.DB) { + _, err := conn.Exec("CREATE DATABASE IF NOT EXISTS power") + if err != nil { + log.Fatal("Failed to create database, ErrMessage: " + err.Error()) + } + _, err = conn.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))") + if err != nil { + log.Fatal("Failed to create stable, ErrMessage: " + err.Error()) + } + _, err = conn.Exec("CREATE TOPIC IF NOT EXISTS topic_meters AS SELECT ts, current, voltage, phase, groupid, location FROM power.meters") + if err != nil { + log.Fatal("Failed to create topic, ErrMessage: " + err.Error()) + } + go func() { + for i := 0; i < 10; i++ { + time.Sleep(time.Second) + _, err = conn.Exec("INSERT INTO power.d1001 USING power.meters TAGS (2, 'California.SanFrancisco') VALUES (NOW , 10.2, 219, 0.32)") + if err != nil { + log.Fatal("Failed to insert data, ErrMessage: " + err.Error()) + } + } + done <- struct{}{} + }() +} From 1590a51e5789b3059e412599375994b940c5c4c4 Mon Sep 17 00:00:00 2001 From: sheyanjie-qq <249478495@qq.com> Date: Fri, 16 Aug 2024 15:18:38 +0800 Subject: [PATCH 12/22] mod rust sample code --- .../com/taos/example/ConsumerLoopFull.java | 2 +- .../rust/nativeexample/examples/insert.rs | 22 ++++----- .../rust/nativeexample/examples/tmq.rs | 46 +++++++++++++++---- .../rust/restexample/examples/insert.rs | 22 ++++----- .../examples/rust/restexample/examples/tmq.rs | 46 +++++++++++++++---- docs/zh/08-develop/05-stmt.md | 4 +- docs/zh/14-reference/05-connector/14-java.mdx | 2 +- 7 files changed, 98 insertions(+), 46 deletions(-) diff --git a/docs/examples/java/src/main/java/com/taos/example/ConsumerLoopFull.java b/docs/examples/java/src/main/java/com/taos/example/ConsumerLoopFull.java index ec9faf383e..a399f3aa6a 100644 --- a/docs/examples/java/src/main/java/com/taos/example/ConsumerLoopFull.java +++ b/docs/examples/java/src/main/java/com/taos/example/ConsumerLoopFull.java @@ -47,7 +47,7 @@ public class ConsumerLoopFull { return consumer; } catch (Exception ex) { // please refer to the JDBC specifications for detailed exceptions info - System.out.printf("Failed to create websocket consumer, host: %s, groupId: %s, clientId: %s, %sErrMessage: %s%n", + System.out.printf("Failed to create native consumer, host: %s, groupId: %s, clientId: %s, %sErrMessage: %s%n", config.getProperty("bootstrap.servers"), config.getProperty("group.id"), config.getProperty("client.id"), diff --git a/docs/examples/rust/nativeexample/examples/insert.rs b/docs/examples/rust/nativeexample/examples/insert.rs index e78381fc61..585cb69c52 100644 --- a/docs/examples/rust/nativeexample/examples/insert.rs +++ b/docs/examples/rust/nativeexample/examples/insert.rs @@ -9,22 +9,22 @@ async fn main() -> anyhow::Result<()> { // ANCHOR: insert_data - match taos.exec(r#"INSERT INTO - power.d1001 USING power.meters TAGS(2,'California.SanFrancisco') - VALUES - (NOW + 1a, 10.30000, 219, 0.31000) - (NOW + 2a, 12.60000, 218, 0.33000) - (NOW + 3a, 12.30000, 221, 0.31000) - power.d1002 USING power.meters TAGS(3, 'California.SanFrancisco') - VALUES - (NOW + 1a, 10.30000, 218, 0.25000) "#).await{ + let insert_sql = r#"INSERT INTO + power.d1001 USING power.meters TAGS(2,'California.SanFrancisco') + VALUES + (NOW + 1a, 10.30000, 219, 0.31000) + (NOW + 2a, 12.60000, 218, 0.33000) + (NOW + 3a, 12.30000, 221, 0.31000) + power.d1002 USING power.meters TAGS(3, 'California.SanFrancisco') + VALUES + (NOW + 1a, 10.30000, 218, 0.25000) "#; + match taos.exec(insert_sql).await{ Ok(affected_rows) => println!("Successfully inserted {} rows to power.meters.", affected_rows), Err(err) => { - eprintln!("Failed to insert data to power.meters, ErrMessage: {}", err); + eprintln!("Failed to insert data to power.meters, sql: {}, ErrMessage: {}", insert_sql, err); return Err(err.into()); } } - // ANCHOR_END: insert_data Ok(()) diff --git a/docs/examples/rust/nativeexample/examples/tmq.rs b/docs/examples/rust/nativeexample/examples/tmq.rs index f312bee0f2..2f8a9e5995 100644 --- a/docs/examples/rust/nativeexample/examples/tmq.rs +++ b/docs/examples/rust/nativeexample/examples/tmq.rs @@ -3,6 +3,8 @@ use std::str::FromStr; use chrono::Local; use chrono::DateTime; use taos::*; +use std::thread; +use tokio::runtime::Runtime; #[tokio::main] async fn main() -> anyhow::Result<()> { @@ -53,17 +55,38 @@ async fn main() -> anyhow::Result<()> { consumer } Err(err) => { - eprintln!("Failed to create websocket consumer, dsn: {}, ErrMessage: {}", dsn, err); + eprintln!("Failed to create native consumer, dsn: {}, groupId: {}, clientId: {}, ErrMessage: {:?}", dsn, group_id, client_id, err); return Err(err.into()); } }; // ANCHOR_END: create_consumer_ac + thread::spawn(move || { + let rt = Runtime::new().unwrap(); + + rt.block_on(async { + let taos_insert = TaosBuilder::from_dsn(&dsn).unwrap().build().await.unwrap(); + for i in 0..50 { + let insert_sql = format!(r#"INSERT INTO + power.d1001 USING power.meters TAGS(2,'California.SanFrancisco') + VALUES + (NOW, 10.30000, {}, 0.31000)"#, i); + if let Err(e) = taos_insert.exec(insert_sql).await { + eprintln!("Failed to execute insert: {:?}", e); + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }); + + }).join().unwrap(); + + // ANCHOR: consume - match consumer.subscribe(["topic_meters"]).await{ + let topic = "topic_meters"; + match consumer.subscribe([topic]).await{ Ok(_) => println!("Subscribe topics successfully."), Err(err) => { - eprintln!("Failed to subscribe topic_meters, ErrMessage: {}", err); + eprintln!("Failed to subscribe topic_meters, ErrMessage: {:?}", err); return Err(err.into()); } } @@ -94,13 +117,14 @@ async fn main() -> anyhow::Result<()> { if let Some(data) = message.into_data() { while let Some(block) = data.fetch_raw_block().await? { let records: Vec = block.deserialize().try_collect()?; + // Add your data processing logic here println!("** read {} records: {:#?}\n", records.len(), records); } } Ok(()) }) .await.map_err(|e| { - eprintln!("Failed to poll data; ErrMessage: {:?}", e); + eprintln!("Failed to poll data, topic: {}, groupId: {}, clientId: {}, ErrMessage: {:?}", topic, group_id, client_id, e); e })?; @@ -110,14 +134,14 @@ async fn main() -> anyhow::Result<()> { consumer .stream() .try_for_each(|(offset, message)| async { - let topic = offset.topic(); // the vgroup id, like partition id in kafka. let vgroup_id = offset.vgroup_id(); - println!("* in vgroup id {vgroup_id} of topic {topic}\n"); + println!("* in vgroup id {} of topic {}\n", vgroup_id, topic); if let Some(data) = message.into_data() { while let Some(block) = data.fetch_raw_block().await? { let records: Vec = block.deserialize().try_collect()?; + // Add your data processing logic here println!("** read {} records: {:#?}\n", records.len(), records); } } @@ -125,14 +149,15 @@ async fn main() -> anyhow::Result<()> { match consumer.commit(offset).await{ Ok(_) => println!("Commit offset manually successfully."), Err(err) => { - eprintln!("Failed to commit offset manually, ErrMessage: {}", err); + eprintln!("Failed to commit offset manually, topic: {}, groupId: {}, clientId: {}, vGroupId: {}, ErrMessage: {:?}", + topic, group_id, client_id, vgroup_id, err); return Err(err.into()); } } Ok(()) }) .await.map_err(|e| { - eprintln!("Failed to poll data, ErrMessage: {:?}", e); + eprintln!("Failed to poll data, topic: {}, groupId: {}, clientId: {}, ErrMessage: {:?}", topic, group_id, client_id, e); e })?; // ANCHOR_END: consumer_commit_manually @@ -152,7 +177,7 @@ async fn main() -> anyhow::Result<()> { let begin = assignment.begin(); let end = assignment.end(); println!( - "topic: {}, vgroup_id: {}, current offset: {} begin {}, end: {}", + "topic: {}, vgroup_id: {}, current offset: {}, begin {}, end: {}", topic, vgroup_id, current, @@ -163,7 +188,8 @@ async fn main() -> anyhow::Result<()> { match consumer.offset_seek(topic, vgroup_id, begin).await{ Ok(_) => (), Err(err) => { - eprintln!("Failed to seek offset, ErrMessage: {}", err); + eprintln!("Failed to seek offset, topic: {}, groupId: {}, clientId: {}, vGroupId: {}, begin: {}, ErrMessage: {:?}", + topic, group_id, client_id, vgroup_id, begin, err); return Err(err.into()); } } diff --git a/docs/examples/rust/restexample/examples/insert.rs b/docs/examples/rust/restexample/examples/insert.rs index 537e531501..be85c1f82c 100644 --- a/docs/examples/rust/restexample/examples/insert.rs +++ b/docs/examples/rust/restexample/examples/insert.rs @@ -9,22 +9,22 @@ async fn main() -> anyhow::Result<()> { // ANCHOR: insert_data - match taos.exec(r#"INSERT INTO - power.d1001 USING power.meters TAGS(2,'California.SanFrancisco') - VALUES - (NOW + 1a, 10.30000, 219, 0.31000) - (NOW + 2a, 12.60000, 218, 0.33000) - (NOW + 3a, 12.30000, 221, 0.31000) - power.d1002 USING power.meters TAGS(3, 'California.SanFrancisco') - VALUES - (NOW + 1a, 10.30000, 218, 0.25000) "#).await{ + let insert_sql = r#"INSERT INTO + power.d1001 USING power.meters TAGS(2,'California.SanFrancisco') + VALUES + (NOW + 1a, 10.30000, 219, 0.31000) + (NOW + 2a, 12.60000, 218, 0.33000) + (NOW + 3a, 12.30000, 221, 0.31000) + power.d1002 USING power.meters TAGS(3, 'California.SanFrancisco') + VALUES + (NOW + 1a, 10.30000, 218, 0.25000) "#; + match taos.exec(insert_sql).await{ Ok(affected_rows) => println!("Successfully inserted {} rows to power.meters.", affected_rows), Err(err) => { - eprintln!("Failed to insert data to power.meters, ErrMessage: {}", dsn, err); + eprintln!("Failed to insert data to power.meters, sql: {}, ErrMessage: {}", insert_sql, err); return Err(err.into()); } } - // ANCHOR_END: insert_data Ok(()) diff --git a/docs/examples/rust/restexample/examples/tmq.rs b/docs/examples/rust/restexample/examples/tmq.rs index 0a0214d258..670ae0ca3c 100644 --- a/docs/examples/rust/restexample/examples/tmq.rs +++ b/docs/examples/rust/restexample/examples/tmq.rs @@ -3,6 +3,8 @@ use std::str::FromStr; use chrono::Local; use chrono::DateTime; use taos::*; +use std::thread; +use tokio::runtime::Runtime; #[tokio::main] async fn main() -> anyhow::Result<()> { @@ -53,17 +55,38 @@ async fn main() -> anyhow::Result<()> { consumer } Err(err) => { - eprintln!("Failed to create websocket consumer, dsn: {}, ErrMessage: {}", dsn, err); + eprintln!("Failed to create websocket consumer, dsn: {}, groupId: {}, clientId: {}, ErrMessage: {:?}", dsn, group_id, client_id, err); return Err(err.into()); } }; // ANCHOR_END: create_consumer_ac + thread::spawn(move || { + let rt = Runtime::new().unwrap(); + + rt.block_on(async { + let taos_insert = TaosBuilder::from_dsn(&dsn).unwrap().build().await.unwrap(); + for i in 0..50 { + let insert_sql = format!(r#"INSERT INTO + power.d1001 USING power.meters TAGS(2,'California.SanFrancisco') + VALUES + (NOW, 10.30000, {}, 0.31000)"#, i); + if let Err(e) = taos_insert.exec(insert_sql).await { + eprintln!("Failed to execute insert: {:?}", e); + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }); + + }).join().unwrap(); + + // ANCHOR: consume - match consumer.subscribe(["topic_meters"]).await{ + let topic = "topic_meters"; + match consumer.subscribe([topic]).await{ Ok(_) => println!("Subscribe topics successfully."), Err(err) => { - eprintln!("Failed to subscribe topic_meters, ErrMessage: {}", err); + eprintln!("Failed to subscribe topic_meters, ErrMessage: {:?}", err); return Err(err.into()); } } @@ -94,13 +117,14 @@ async fn main() -> anyhow::Result<()> { if let Some(data) = message.into_data() { while let Some(block) = data.fetch_raw_block().await? { let records: Vec = block.deserialize().try_collect()?; + // Add your data processing logic here println!("** read {} records: {:#?}\n", records.len(), records); } } Ok(()) }) .await.map_err(|e| { - eprintln!("Failed to poll data; ErrMessage: {:?}", e); + eprintln!("Failed to poll data, topic: {}, groupId: {}, clientId: {}, ErrMessage: {:?}", topic, group_id, client_id, e); e })?; @@ -110,14 +134,14 @@ async fn main() -> anyhow::Result<()> { consumer .stream() .try_for_each(|(offset, message)| async { - let topic = offset.topic(); // the vgroup id, like partition id in kafka. let vgroup_id = offset.vgroup_id(); - println!("* in vgroup id {vgroup_id} of topic {topic}\n"); + println!("* in vgroup id {} of topic {}\n", vgroup_id, topic); if let Some(data) = message.into_data() { while let Some(block) = data.fetch_raw_block().await? { let records: Vec = block.deserialize().try_collect()?; + // Add your data processing logic here println!("** read {} records: {:#?}\n", records.len(), records); } } @@ -125,14 +149,15 @@ async fn main() -> anyhow::Result<()> { match consumer.commit(offset).await{ Ok(_) => println!("Commit offset manually successfully."), Err(err) => { - eprintln!("Failed to commit offset manually, ErrMessage: {}", err); + eprintln!("Failed to commit offset manually, topic: {}, groupId: {}, clientId: {}, vGroupId: {}, ErrMessage: {:?}", + topic, group_id, client_id, vgroup_id, err); return Err(err.into()); } } Ok(()) }) .await.map_err(|e| { - eprintln!("Failed to poll data, ErrMessage: {:?}", e); + eprintln!("Failed to poll data, topic: {}, groupId: {}, clientId: {}, ErrMessage: {:?}", topic, group_id, client_id, e); e })?; // ANCHOR_END: consumer_commit_manually @@ -152,7 +177,7 @@ async fn main() -> anyhow::Result<()> { let begin = assignment.begin(); let end = assignment.end(); println!( - "topic: {}, vgroup_id: {}, current offset: {} begin {}, end: {}", + "topic: {}, vgroup_id: {}, current offset: {}, begin {}, end: {}", topic, vgroup_id, current, @@ -163,7 +188,8 @@ async fn main() -> anyhow::Result<()> { match consumer.offset_seek(topic, vgroup_id, begin).await{ Ok(_) => (), Err(err) => { - eprintln!("Failed to seek offset, ErrMessage: {}", err); + eprintln!("Failed to seek offset, topic: {}, groupId: {}, clientId: {}, vGroupId: {}, begin: {}, ErrMessage: {:?}", + topic, group_id, client_id, vgroup_id, begin, err); return Err(err.into()); } } diff --git a/docs/zh/08-develop/05-stmt.md b/docs/zh/08-develop/05-stmt.md index 9dfd9f56e3..e659177c94 100644 --- a/docs/zh/08-develop/05-stmt.md +++ b/docs/zh/08-develop/05-stmt.md @@ -31,7 +31,7 @@ import TabItem from "@theme/TabItem"; ``` -这是一个[更详细的参数绑定示例](https://github.com/taosdata/TDengine/blob/main/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/WSParameterBindingFullDemo.java) +这是一个[更详细的参数绑定示例](https://github.com/taosdata/TDengine/blob/main/docs/examples/java/src/main/java/com/taos/example/WSParameterBindingFullDemo.java) @@ -79,7 +79,7 @@ import TabItem from "@theme/TabItem"; {{#include docs/examples/java/src/main/java/com/taos/example/ParameterBindingBasicDemo.java:para_bind}} ``` -这是一个[更详细的参数绑定示例](https://github.com/taosdata/TDengine/blob/main/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/ParameterBindingFullDemo.java) +这是一个[更详细的参数绑定示例](https://github.com/taosdata/TDengine/blob/main/docs/examples/java/src/main/java/com/taos/example/ParameterBindingFullDemo.java) diff --git a/docs/zh/14-reference/05-connector/14-java.mdx b/docs/zh/14-reference/05-connector/14-java.mdx index f355aea621..a752867b3f 100644 --- a/docs/zh/14-reference/05-connector/14-java.mdx +++ b/docs/zh/14-reference/05-connector/14-java.mdx @@ -141,7 +141,7 @@ TDengine 目前支持时间戳、数字、字符、布尔类型,与 Java 对 由于历史原因,TDengine中的BINARY底层不是真正的二进制数据,已不建议使用。请用VARBINARY类型代替。 GEOMETRY类型是little endian字节序的二进制数据,符合WKB规范。详细信息请参考 [数据类型](../../taos-sql/data-type/#数据类型) WKB规范请参考[Well-Known Binary (WKB)](https://libgeos.org/specifications/wkb/) -对于java连接器,可以使用jts库来方便的创建GEOMETRY类型对象,序列化后写入TDengine,这里有一个样例[Geometry示例](https://github.com/taosdata/TDengine/blob/3.0/examples/JDBC/JDBCDemo/src/main/java/com/taosdata/example/GeometryDemo.java) +对于java连接器,可以使用jts库来方便的创建GEOMETRY类型对象,序列化后写入TDengine,这里有一个样例[Geometry示例](https://github.com/taosdata/TDengine/blob/main/docs/examples/java/src/main/java/com/taos/example/GeometryDemo.java) ## 示例程序汇总 From 8c368a6fa665a1dafb18532dae364a49622d3bf4 Mon Sep 17 00:00:00 2001 From: t_max <1172915550@qq.com> Date: Fri, 16 Aug 2024 15:22:18 +0800 Subject: [PATCH 13/22] docs: update the output of go and c# examples --- docs/examples/csharp/subscribe/Program.cs | 42 +++++++++++---------- docs/examples/csharp/wssubscribe/Program.cs | 31 ++++++++------- docs/examples/go/tmq/native/main.go | 2 +- docs/examples/go/tmq/ws/main.go | 2 +- 4 files changed, 42 insertions(+), 35 deletions(-) diff --git a/docs/examples/csharp/subscribe/Program.cs b/docs/examples/csharp/subscribe/Program.cs index 2ec73aae48..50988d0c5d 100644 --- a/docs/examples/csharp/subscribe/Program.cs +++ b/docs/examples/csharp/subscribe/Program.cs @@ -111,11 +111,12 @@ namespace TMQExample catch (Exception e) { // handle other exceptions - Console.WriteLine($"Failed to create native consumer, " + - $"host: {_host}, " + - $"groupId: {_groupId}, " + - $"clientId: {_clientId}, " + - $"ErrMessage: {e.Message}"); + Console.WriteLine( + $"Failed to create native consumer, " + + $"host: {_host}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}, " + + $"ErrMessage: {e.Message}"); throw; } @@ -163,11 +164,12 @@ namespace TMQExample catch (Exception e) { // handle other exceptions - Console.WriteLine($"Failed to poll data, " + - $"topic: {_topic}, " + - $"groupId: {_groupId}, " + - $"clientId: {_clientId}, " + - $"ErrMessage: {e.Message}"); + Console.WriteLine( + $"Failed to poll data, " + + $"topic: {_topic}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}, " + + $"ErrMessage: {e.Message}"); throw; } // ANCHOR_END: subscribe @@ -186,13 +188,14 @@ namespace TMQExample { consumer.Seek(new TopicPartitionOffset(topicPartition.Topic, topicPartition.Partition, 0)); } + Console.WriteLine("Assignment seek to beginning successfully"); } catch (TDengineError e) { // handle TDengine error Console.WriteLine( - $"Failed to execute seek example, " + + $"Failed to seek offset, " + $"topic: {_topic}, " + $"groupId: {_groupId}, " + $"clientId: {_clientId}, " + @@ -204,12 +207,13 @@ namespace TMQExample catch (Exception e) { // handle other exceptions - Console.WriteLine($"Failed to execute seek example, " + - $"topic: {_topic}, " + - $"groupId: {_groupId}, " + - $"clientId: {_clientId}, " + - $"offset: 0, " + - $"ErrMessage: {e.Message}"); + Console.WriteLine( + $"Failed to seek offset, " + + $"topic: {_topic}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}, " + + $"offset: 0, " + + $"ErrMessage: {e.Message}"); throw; } // ANCHOR_END: seek @@ -240,7 +244,7 @@ namespace TMQExample { // handle TDengine error Console.WriteLine( - $"Failed to execute commit example, " + + $"Failed to commit offset, " + $"topic: {_topic}, " + $"groupId: {_groupId}, " + $"clientId: {_clientId}, " + @@ -253,7 +257,7 @@ namespace TMQExample { // handle other exceptions Console.WriteLine( - $"Failed to execute commit example, " + + $"Failed to commit offset, " + $"topic: {_topic}, " + $"groupId: {_groupId}, " + $"clientId: {_clientId}, " + diff --git a/docs/examples/csharp/wssubscribe/Program.cs b/docs/examples/csharp/wssubscribe/Program.cs index 5f5afc575a..939189cabd 100644 --- a/docs/examples/csharp/wssubscribe/Program.cs +++ b/docs/examples/csharp/wssubscribe/Program.cs @@ -116,11 +116,12 @@ namespace TMQExample catch (Exception e) { // handle other exceptions - Console.WriteLine($"Failed to create native consumer, " + - $"host: {_host}, " + - $"groupId: {_groupId}, " + - $"clientId: {_clientId}, " + - $"ErrMessage: {e.Message}"); + Console.WriteLine( + $"Failed to create native consumer, " + + $"host: {_host}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}, " + + $"ErrMessage: {e.Message}"); throw; } @@ -191,13 +192,14 @@ namespace TMQExample { consumer.Seek(new TopicPartitionOffset(topicPartition.Topic, topicPartition.Partition, 0)); } + Console.WriteLine("Assignment seek to beginning successfully"); } catch (TDengineError e) { // handle TDengine error Console.WriteLine( - $"Failed to execute seek example, " + + $"Failed to seek offset, " + $"topic: {_topic}, " + $"groupId: {_groupId}, " + $"clientId: {_clientId}, " + @@ -209,12 +211,13 @@ namespace TMQExample catch (Exception e) { // handle other exceptions - Console.WriteLine($"Failed to execute seek example, " + - $"topic: {_topic}, " + - $"groupId: {_groupId}, " + - $"clientId: {_clientId}, " + - $"offset: 0, " + - $"ErrMessage: {e.Message}"); + Console.WriteLine( + $"Failed to seek offset, " + + $"topic: {_topic}, " + + $"groupId: {_groupId}, " + + $"clientId: {_clientId}, " + + $"offset: 0, " + + $"ErrMessage: {e.Message}"); throw; } // ANCHOR_END: seek @@ -245,7 +248,7 @@ namespace TMQExample { // handle TDengine error Console.WriteLine( - $"Failed to execute commit example, " + + $"Failed to commit offset, " + $"topic: {_topic}, " + $"groupId: {_groupId}, " + $"clientId: {_clientId}, " + @@ -258,7 +261,7 @@ namespace TMQExample { // handle other exceptions Console.WriteLine( - $"Failed to execute commit example, " + + $"Failed to commit offset, " + $"topic: {_topic}, " + $"groupId: {_groupId}, " + $"clientId: {_clientId}, " + diff --git a/docs/examples/go/tmq/native/main.go b/docs/examples/go/tmq/native/main.go index 1d4a22b880..8d667abc18 100644 --- a/docs/examples/go/tmq/native/main.go +++ b/docs/examples/go/tmq/native/main.go @@ -112,7 +112,7 @@ func main() { }, 0) if err != nil { log.Fatalf( - "Failed to execute seek example, topic: %s, groupId: %s, clientId: %s, partition: %d, offset: %d, ErrMessage: %s\n", + "Failed to execute seek offset, topic: %s, groupId: %s, clientId: %s, partition: %d, offset: %d, ErrMessage: %s\n", topic, groupID, clientID, diff --git a/docs/examples/go/tmq/ws/main.go b/docs/examples/go/tmq/ws/main.go index aaed8395e0..9ea4d72b39 100644 --- a/docs/examples/go/tmq/ws/main.go +++ b/docs/examples/go/tmq/ws/main.go @@ -130,7 +130,7 @@ func main() { }, 0) if err != nil { log.Fatalf( - "Failed to execute seek example, topic: %s, groupId: %s, clientId: %s, partition: %d, offset: %d, ErrMessage: %s\n", + "Failed to seek offset, topic: %s, groupId: %s, clientId: %s, partition: %d, offset: %d, ErrMessage: %s\n", topic, groupID, clientID, From 3b7b41f82d3524a77588a92371b0898e84a0e9ce Mon Sep 17 00:00:00 2001 From: Yaming Pei Date: Fri, 16 Aug 2024 17:10:21 +0800 Subject: [PATCH 14/22] c language sample program modification --- docs/examples/c/connect_example.c | 4 +- docs/examples/c/create_db_demo.c | 10 +- docs/examples/c/insert_data_demo.c | 6 +- docs/examples/c/query_data_demo.c | 17 ++- docs/examples/c/sml_insert_demo.c | 23 ++-- docs/examples/c/stmt_insert_demo.c | 10 +- docs/examples/c/tmq_demo.c | 168 ++++++++++++++++------------- docs/examples/c/with_reqid_demo.c | 19 ++-- 8 files changed, 135 insertions(+), 122 deletions(-) diff --git a/docs/examples/c/connect_example.c b/docs/examples/c/connect_example.c index 53d2d0d59b..ef07c54122 100644 --- a/docs/examples/c/connect_example.c +++ b/docs/examples/c/connect_example.c @@ -12,11 +12,11 @@ int main() { uint16_t port = 6030; // 0 means use the default port TAOS *taos = taos_connect(host, user, passwd, db, port); if (taos == NULL) { - printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL)); + fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL)); taos_cleanup(); return -1; } - printf("Connected to %s:%hu successfully.\n", host, port); + fprintf(stdout, "Connected to %s:%hu successfully.\n", host, port); /* put your code here for read and write */ diff --git a/docs/examples/c/create_db_demo.c b/docs/examples/c/create_db_demo.c index 44960defa5..7ae41da65c 100644 --- a/docs/examples/c/create_db_demo.c +++ b/docs/examples/c/create_db_demo.c @@ -33,7 +33,7 @@ static int DemoCreateDB() { // connect TAOS *taos = taos_connect(host, user, password, NULL, port); if (taos == NULL) { - printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), + fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL)); taos_cleanup(); return -1; @@ -43,13 +43,13 @@ static int DemoCreateDB() { TAOS_RES *result = taos_query(taos, "CREATE DATABASE IF NOT EXISTS power"); code = taos_errno(result); if (code != 0) { - printf("Failed to create database power, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(result)); + fprintf(stderr, "Failed to create database power, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(result)); taos_close(taos); taos_cleanup(); return -1; } taos_free_result(result); - printf("Create database power successfully.\n"); + fprintf(stdout, "Create database power successfully.\n"); // create table const char *sql = @@ -58,13 +58,13 @@ static int DemoCreateDB() { result = taos_query(taos, sql); code = taos_errno(result); if (code != 0) { - printf("Failed to create stable power.meters, ErrCode: 0x%x, ErrMessage: %s\n.", code, taos_errstr(result)); + fprintf(stderr, "Failed to create stable power.meters, ErrCode: 0x%x, ErrMessage: %s\n.", code, taos_errstr(result)); taos_close(taos); taos_cleanup(); return -1; } taos_free_result(result); - printf("Create stable power.meters successfully.\n"); + fprintf(stdout, "Create stable power.meters successfully.\n"); // close & clean taos_close(taos); diff --git a/docs/examples/c/insert_data_demo.c b/docs/examples/c/insert_data_demo.c index e880af0cd6..7570af02ad 100644 --- a/docs/examples/c/insert_data_demo.c +++ b/docs/examples/c/insert_data_demo.c @@ -33,7 +33,7 @@ static int DemoInsertData() { // connect TAOS *taos = taos_connect(host, user, password, NULL, port); if (taos == NULL) { - printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), + fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL)); taos_cleanup(); return -1; @@ -53,7 +53,7 @@ static int DemoInsertData() { TAOS_RES *result = taos_query(taos, sql); code = taos_errno(result); if (code != 0) { - printf("Failed to insert data to power.meters, ErrCode: 0x%x, ErrMessage: %s\n.", code, taos_errstr(result)); + fprintf(stderr, "Failed to insert data to power.meters, sql: %s, ErrCode: 0x%x, ErrMessage: %s\n.", sql, code, taos_errstr(result)); taos_close(taos); taos_cleanup(); return -1; @@ -62,7 +62,7 @@ static int DemoInsertData() { // you can check affectedRows here int rows = taos_affected_rows(result); - printf("Successfully inserted %d rows into power.meters.\n", rows); + fprintf(stdout, "Successfully inserted %d rows into power.meters.\n", rows); // close & clean taos_close(taos); diff --git a/docs/examples/c/query_data_demo.c b/docs/examples/c/query_data_demo.c index 097a6b99b8..0e13f57e3f 100644 --- a/docs/examples/c/query_data_demo.c +++ b/docs/examples/c/query_data_demo.c @@ -33,7 +33,7 @@ static int DemoQueryData() { // connect TAOS *taos = taos_connect(host, user, password, NULL, port); if (taos == NULL) { - printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), + fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL)); taos_cleanup(); return -1; @@ -44,7 +44,7 @@ static int DemoQueryData() { TAOS_RES *result = taos_query(taos, sql); code = taos_errno(result); if (code != 0) { - printf("Failed to query data from power.meters, sql: %s, ErrCode: 0x%x, ErrMessage: %s\n.", sql, code, + fprintf(stderr, "Failed to query data from power.meters, sql: %s, ErrCode: 0x%x, ErrMessage: %s\n.", sql, code, taos_errstr(result)); taos_close(taos); taos_cleanup(); @@ -56,20 +56,15 @@ static int DemoQueryData() { int num_fields = taos_field_count(result); TAOS_FIELD *fields = taos_fetch_fields(result); - printf("fields: %d\n", num_fields); - printf("sql: %s, result:\n", sql); + fprintf(stdout, "query successfully, got %d fields, the sql is: %s.\n", num_fields, sql); // fetch the records row by row while ((row = taos_fetch_row(result))) { - char temp[1024] = {0}; - if (taos_print_row(temp, row, fields, num_fields) < 0) { - printf("Failed to print row\n"); - break; - } - printf("%s\n", temp); + // Add your data processing logic here + rows++; } - printf("total rows: %d\n", rows); + fprintf(stdout, "total rows: %d\n", rows); taos_free_result(result); // close & clean diff --git a/docs/examples/c/sml_insert_demo.c b/docs/examples/c/sml_insert_demo.c index 9adbb28f87..63870d90b6 100644 --- a/docs/examples/c/sml_insert_demo.c +++ b/docs/examples/c/sml_insert_demo.c @@ -32,7 +32,7 @@ static int DemoSmlInsert() { // connect TAOS *taos = taos_connect(host, user, password, NULL, port); if (taos == NULL) { - printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), + fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL)); taos_cleanup(); return -1; @@ -42,7 +42,7 @@ static int DemoSmlInsert() { TAOS_RES *result = taos_query(taos, "CREATE DATABASE IF NOT EXISTS power"); code = taos_errno(result); if (code != 0) { - printf("Failed to create database power, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(result)); + fprintf(stderr, "Failed to create database power, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(result)); taos_close(taos); taos_cleanup(); return -1; @@ -53,7 +53,7 @@ static int DemoSmlInsert() { result = taos_query(taos, "USE power"); code = taos_errno(result); if (code != 0) { - printf("Failed to execute use power, ErrCode: 0x%x, ErrMessage: %s\n.", code, taos_errstr(result)); + fprintf(stderr, "Failed to execute use power, ErrCode: 0x%x, ErrMessage: %s\n.", code, taos_errstr(result)); taos_close(taos); taos_cleanup(); return -1; @@ -74,7 +74,7 @@ static int DemoSmlInsert() { result = taos_schemaless_insert(taos, lines, 1, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_MILLI_SECONDS); code = taos_errno(result); if (code != 0) { - printf("Failed to insert schemaless line data, data: %s, ErrCode: 0x%x, ErrMessage: %s\n.", line_demo, code, + fprintf(stderr, "Failed to insert schemaless line data, data: %s, ErrCode: 0x%x, ErrMessage: %s\n.", line_demo, code, taos_errstr(result)); taos_close(taos); taos_cleanup(); @@ -82,7 +82,7 @@ static int DemoSmlInsert() { } int rows = taos_affected_rows(result); - printf("Insert %d rows of schemaless line data successfully.\n", rows); + fprintf(stdout, "Insert %d rows of schemaless line data successfully.\n", rows); taos_free_result(result); // opentsdb telnet protocol @@ -90,7 +90,7 @@ static int DemoSmlInsert() { result = taos_schemaless_insert(taos, telnets, 1, TSDB_SML_TELNET_PROTOCOL, TSDB_SML_TIMESTAMP_MILLI_SECONDS); code = taos_errno(result); if (code != 0) { - printf("Failed to insert schemaless telnet data, data: %s, ErrCode: 0x%x, ErrMessage: %s\n.", telnet_demo, code, + fprintf(stderr, "Failed to insert schemaless telnet data, data: %s, ErrCode: 0x%x, ErrMessage: %s\n.", telnet_demo, code, taos_errstr(result)); taos_close(taos); taos_cleanup(); @@ -98,15 +98,16 @@ static int DemoSmlInsert() { } rows = taos_affected_rows(result); - printf("Insert %d rows of schemaless telnet data successfully.\n", rows); + fprintf(stdout, "Insert %d rows of schemaless telnet data successfully.\n", rows); taos_free_result(result); // opentsdb json protocol char *jsons[1] = {0}; // allocate memory for json data. can not use static memory. - jsons[0] = malloc(1024); + size_t size = 1024; + jsons[0] = malloc(size); if (jsons[0] == NULL) { - printf("Failed to allocate memory\n"); + fprintf(stderr, "Failed to allocate memory: %zu bytes.\n", size); taos_close(taos); taos_cleanup(); return -1; @@ -116,7 +117,7 @@ static int DemoSmlInsert() { code = taos_errno(result); if (code != 0) { free(jsons[0]); - printf("Failed to insert schemaless json data, Server: %s, ErrCode: 0x%x, ErrMessage: %s\n.", json_demo, code, + fprintf(stderr, "Failed to insert schemaless json data, Server: %s, ErrCode: 0x%x, ErrMessage: %s\n.", json_demo, code, taos_errstr(result)); taos_close(taos); taos_cleanup(); @@ -125,7 +126,7 @@ static int DemoSmlInsert() { free(jsons[0]); rows = taos_affected_rows(result); - printf("Insert %d rows of schemaless json data successfully.\n", rows); + fprintf(stdout, "Insert %d rows of schemaless json data successfully.\n", rows); taos_free_result(result); // close & clean diff --git a/docs/examples/c/stmt_insert_demo.c b/docs/examples/c/stmt_insert_demo.c index 854c9f86e2..f89a0fc8da 100644 --- a/docs/examples/c/stmt_insert_demo.c +++ b/docs/examples/c/stmt_insert_demo.c @@ -32,7 +32,7 @@ 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)); + fprintf(stderr, "%s\n", taos_errstr(res)); taos_free_result(res); taos_close(taos); exit(EXIT_FAILURE); @@ -49,7 +49,7 @@ void executeSQL(TAOS *taos, const char *sql) { */ void checkErrorCode(TAOS_STMT *stmt, int code, const char *msg) { if (code != 0) { - printf("%s. code: %d, error: %s\n", msg,code,taos_stmt_errstr(stmt)); + fprintf(stderr, "%s. code: %d, error: %s\n", msg,code,taos_stmt_errstr(stmt)); taos_stmt_close(stmt); exit(EXIT_FAILURE); } @@ -74,7 +74,7 @@ void insertData(TAOS *taos) { // init TAOS_STMT *stmt = taos_stmt_init(taos); if (stmt == NULL) { - printf("Failed to init taos_stmt, error: %s\n", taos_stmt_errstr(NULL)); + fprintf(stderr, "Failed to init taos_stmt, error: %s\n", taos_stmt_errstr(NULL)); exit(EXIT_FAILURE); } // prepare @@ -159,7 +159,7 @@ void insertData(TAOS *taos) { int affected = taos_stmt_affected_rows_once(stmt); total_affected += affected; } - printf("Successfully inserted %d rows to power.meters.\n", total_affected); + fprintf(stdout, "Successfully inserted %d rows to power.meters.\n", total_affected); taos_stmt_close(stmt); } @@ -170,7 +170,7 @@ int main() { uint16_t port = 6030; TAOS *taos = taos_connect(host, user, password, NULL, port); if (taos == NULL) { - printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL)); + fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL)); taos_cleanup(); exit(EXIT_FAILURE); } diff --git a/docs/examples/c/tmq_demo.c b/docs/examples/c/tmq_demo.c index e8e28e1df4..9deff9add5 100644 --- a/docs/examples/c/tmq_demo.c +++ b/docs/examples/c/tmq_demo.c @@ -26,6 +26,7 @@ volatile int thread_stop = 0; static int running = 1; +static int count = 0; const char* topic_name = "topic_meters"; typedef struct { @@ -40,6 +41,18 @@ typedef struct { const char* auto_offset_reset; } ConsumerConfig; +ConsumerConfig config = { + .enable_auto_commit = "true", + .auto_commit_interval_ms = "1000", + .group_id = "group1", + .client_id = "client1", + .td_connect_host = "localhost", + .td_connect_port = "6030", + .td_connect_user = "root", + .td_connect_pass = "taosdata", + .auto_offset_reset = "latest" +}; + void* prepare_data(void* arg) { const char* host = "localhost"; const char* user = "root"; @@ -48,8 +61,7 @@ void* prepare_data(void* arg) { int code = 0; TAOS* pConn = taos_connect(host, user, password, NULL, port); if (pConn == NULL) { - fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), - taos_errstr(NULL)); + fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL)); taos_cleanup(); return NULL; } @@ -69,8 +81,7 @@ void* prepare_data(void* arg) { pRes = taos_query(pConn, buf); code = taos_errno(pRes); if (code != 0) { - fprintf(stderr, "Failed to insert data to power.meters, ErrCode: 0x%x, ErrMessage: %s.\n", code, - taos_errstr(pRes)); + fprintf(stderr, "Failed to insert data to power.meters, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes)); } taos_free_result(pRes); sleep(1); @@ -80,43 +91,28 @@ void* prepare_data(void* arg) { } // ANCHOR: msg_process -static int32_t msg_process(TAOS_RES* msg) { +int32_t msg_process(TAOS_RES* msg) { char buf[1024]; // buf to store the row content int32_t rows = 0; const char* topicName = tmq_get_topic_name(msg); - const char* dbName = tmq_get_db_name(msg); - int32_t vgroupId = tmq_get_vgroup_id(msg); + const char* dbName = tmq_get_db_name(msg); + int32_t vgroupId = tmq_get_vgroup_id(msg); - fprintf(stdout, "topic: %s\n", topicName); - fprintf(stdout, "db: %s\n", dbName); - fprintf(stdout, "vgroup id: %d\n", vgroupId); - - while (1) { + while (true) { // get one row data from message TAOS_ROW row = taos_fetch_row(msg); if (row == NULL) break; - // get the field information - TAOS_FIELD* fields = taos_fetch_fields(msg); - // get the number of fields - int32_t numOfFields = taos_field_count(msg); - // get the precision of the result - int32_t precision = taos_result_precision(msg); + // Add your data processing logic here + rows++; - // print the row content - if (taos_print_row(buf, row, fields, numOfFields) < 0) { - fprintf(stderr, "Failed to print row\n"); - break; - } - // print the precision and row content to the console - fprintf(stdout, "precision: %d, data: %s\n", precision, buf); } return rows; } // ANCHOR_END: msg_process -static int32_t init_env() { +TAOS* init_env() { const char* host = "localhost"; const char* user = "root"; const char* password = "taosdata"; @@ -124,10 +120,9 @@ static int32_t init_env() { int code = 0; TAOS* pConn = taos_connect(host, user, password, NULL, port); if (pConn == NULL) { - fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), - taos_errstr(NULL)); + fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL)); taos_cleanup(); - return -1; + return NULL; } TAOS_RES* pRes; @@ -136,6 +131,7 @@ static int32_t init_env() { code = taos_errno(pRes); if (code != 0) { fprintf(stderr, "Failed to drop topic_meters, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes)); + goto END; } taos_free_result(pRes); @@ -143,6 +139,7 @@ static int32_t init_env() { code = taos_errno(pRes); if (code != 0) { fprintf(stderr, "Failed to drop database power, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes)); + goto END; } taos_free_result(pRes); @@ -150,7 +147,7 @@ static int32_t init_env() { pRes = taos_query(pConn, "CREATE DATABASE power PRECISION 'ms' WAL_RETENTION_PERIOD 3600"); code = taos_errno(pRes); if (code != 0) { - fprintf(stderr, "Failed to create tmqdb, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes)); + fprintf(stderr, "Failed to create power, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes)); goto END; } taos_free_result(pRes); @@ -165,56 +162,78 @@ static int32_t init_env() { fprintf(stderr, "Failed to create super table meters, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes)); goto END; } - taos_free_result(pRes); - taos_close(pConn); - return 0; + + return pConn; END: taos_free_result(pRes); taos_close(pConn); - return -1; + return NULL; } -int32_t create_topic() { +void deinit_env(TAOS* pConn) { + if (pConn) + taos_close(pConn); +} + +int32_t create_topic(TAOS* pConn) { TAOS_RES* pRes; - const char* host = "localhost"; - const char* user = "root"; - const char* password = "taosdata"; - uint16_t port = 6030; int code = 0; - TAOS* pConn = taos_connect(host, user, password, NULL, port); - if (pConn == NULL) { - fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), - taos_errstr(NULL)); - taos_cleanup(); + + if (!pConn) { + fprintf(stderr, "Invalid input parameter.\n"); return -1; } - pRes = taos_query(pConn, "USE POWER"); + pRes = taos_query(pConn, "USE power"); code = taos_errno(pRes); if (taos_errno(pRes) != 0) { - fprintf(stderr, "Failed to use tmqdb, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes)); + fprintf(stderr, "Failed to use power, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes)); return -1; } taos_free_result(pRes); - pRes = taos_query( - pConn, - "CREATE TOPIC IF NOT EXISTS topic_meters AS SELECT ts, current, voltage, phase, groupid, location FROM meters"); + pRes = taos_query(pConn, "CREATE TOPIC IF NOT EXISTS topic_meters AS SELECT ts, current, voltage, phase, groupid, location FROM meters"); code = taos_errno(pRes); if (code != 0) { fprintf(stderr, "Failed to create topic topic_meters, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes)); return -1; } taos_free_result(pRes); + return 0; +} - taos_close(pConn); +int32_t drop_topic(TAOS* pConn) { + TAOS_RES* pRes; + int code = 0; + + if (!pConn) { + fprintf(stderr, "Invalid input parameter.\n"); + return -1; + } + + pRes = taos_query(pConn, "USE power"); + code = taos_errno(pRes); + if (taos_errno(pRes) != 0) { + fprintf(stderr, "Failed to use power, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes)); + return -1; + } + taos_free_result(pRes); + + pRes = taos_query(pConn, "DROP TOPIC IF EXISTS topic_meters"); + code = taos_errno(pRes); + if (code != 0) { + fprintf(stderr, "Failed to drop topic topic_meters, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes)); + return -1; + } + taos_free_result(pRes); return 0; } void tmq_commit_cb_print(tmq_t* tmq, int32_t code, void* param) { - fprintf(stdout, "tmq_commit_cb_print() code: %d, tmq: %p, param: %p\n", code, tmq, param); + count +=1; + fprintf(stdout, "tmq_commit_cb_print() code: %d, tmq: %p, param: %p, count: %d.\n", code, tmq, param, count); } // ANCHOR: create_consumer_1 @@ -289,7 +308,6 @@ _end: tmq_list_t* build_topic_list() { // create a empty topic list tmq_list_t* topicList = tmq_list_new(); - const char* topic_name = "topic_meters"; // append topic name to the list int32_t code = tmq_list_append(topicList, topic_name); @@ -315,8 +333,10 @@ void basic_consume_loop(tmq_t* tmq) { TAOS_RES* tmqmsg = tmq_consumer_poll(tmq, timeout); if (tmqmsg) { msgCnt++; - // process the message + + // Add your data processing logic here totalRows += msg_process(tmqmsg); + // free the message taos_free_result(tmqmsg); } @@ -349,12 +369,13 @@ void consume_repeatly(tmq_t* tmq) { code = tmq_offset_seek(tmq, topic_name, p->vgId, p->begin); if (code != 0) { - fprintf(stderr, "Failed to seek assignment %d to beginning %ld, ErrCode: 0x%x, ErrMessage: %s.\n", i, p->begin, - code, tmq_err2str(code)); - } else { - fprintf(stdout, "Seek assignment %d to beginning %ld successfully.\n", i, p->begin); + fprintf(stderr, "Failed to seek offset, topic: %s, groupId: %s, clientId: %s, ErrCode: 0x%x, ErrMessage: %s.\n", + topic_name, config.group_id, config.client_id, code, tmq_err2str(code)); + break; } } + if (code == 0) + fprintf(stdout, "Assignment seek to beginning successfully.\n"); // free the assignment array tmq_free_assignment(pAssign); @@ -380,7 +401,8 @@ void manual_commit(tmq_t* tmq) { // commit the message int32_t code = tmq_commit_sync(tmq, tmqmsg); if (code) { - fprintf(stderr, "Failed to commit message, ErrCode: 0x%x, ErrMessage: %s.\n", code, tmq_err2str(code)); + fprintf(stderr, "Failed to commit offset, topic: %s, groupId: %s, clientId: %s, ErrCode: 0x%x, ErrMessage: %s.\n", + topic_name, config.group_id, config.client_id, code, tmq_err2str(code)); // free the message taos_free_result(tmqmsg); break; @@ -405,11 +427,14 @@ int main(int argc, char* argv[]) { int32_t code; pthread_t thread_id; - if (init_env() < 0) { + TAOS* pConn = init_env(); + if (pConn == NULL) { + fprintf(stderr, "Failed to init env.\n"); return -1; } - if (create_topic() < 0) { + if (create_topic(pConn) < 0) { + fprintf(stderr, "Failed to create topic.\n"); return -1; } @@ -418,16 +443,6 @@ int main(int argc, char* argv[]) { return -1; } - ConsumerConfig config = {.enable_auto_commit = "true", - .auto_commit_interval_ms = "1000", - .group_id = "group1", - .client_id = "client1", - .td_connect_host = "localhost", - .td_connect_port = "6030", - .td_connect_user = "root", - .td_connect_pass = "taosdata", - .auto_offset_reset = "latest"}; - // ANCHOR: create_consumer_2 tmq_t* tmq = build_consumer(&config); if (NULL == tmq) { @@ -435,8 +450,8 @@ int main(int argc, char* argv[]) { config.td_connect_host, config.group_id, config.client_id); return -1; } else { - fprintf(stdout, "Create consumer successfully, host: %s, groupId: %s, , clientId: %s.\n", config.td_connect_host, - config.group_id, config.client_id); + fprintf(stdout, "Create consumer successfully, host: %s, groupId: %s, clientId: %s.\n", + config.td_connect_host, config.group_id, config.client_id); } // ANCHOR_END: create_consumer_2 @@ -467,7 +482,8 @@ int main(int argc, char* argv[]) { // unsubscribe the topic code = tmq_unsubscribe(tmq); if (code) { - fprintf(stderr, "Failed to unsubscribe consumer, ErrCode: 0x%x, ErrMessage: %s.\n", code, tmq_err2str(code)); + fprintf(stderr, "Failed to unsubscribe consumer, topic: %s, groupId: %s, clientId: %s, ErrCode: 0x%x, ErrMessage: %s.\n", + topic_name, config.group_id, config.client_id, code, tmq_err2str(code)); } else { fprintf(stderr, "Consumer unsubscribed successfully.\n"); } @@ -484,5 +500,11 @@ int main(int argc, char* argv[]) { thread_stop = 1; pthread_join(thread_id, NULL); + if (drop_topic(pConn) < 0) { + fprintf(stderr, "Failed to drop topic.\n"); + return -1; + } + + deinit_env(pConn); return 0; } diff --git a/docs/examples/c/with_reqid_demo.c b/docs/examples/c/with_reqid_demo.c index c6e87686e9..8942077f67 100644 --- a/docs/examples/c/with_reqid_demo.c +++ b/docs/examples/c/with_reqid_demo.c @@ -33,8 +33,7 @@ static int DemoWithReqId() { // connect TAOS *taos = taos_connect(host, user, password, NULL, port); if (taos == NULL) { - printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), - taos_errstr(NULL)); + fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL)); taos_cleanup(); return -1; } @@ -45,7 +44,7 @@ static int DemoWithReqId() { TAOS_RES *result = taos_query_with_reqid(taos, sql, reqid); code = taos_errno(result); if (code != 0) { - printf("Failed to execute sql with reqId: %ld, ErrCode: 0x%x, ErrMessage: %s\n.", reqid, code, taos_errstr(result)); + fprintf(stderr, "Failed to execute sql with reqId: %ld, ErrCode: 0x%x, ErrMessage: %s\n.", reqid, code, taos_errstr(result)); taos_close(taos); taos_cleanup(); return -1; @@ -56,20 +55,16 @@ static int DemoWithReqId() { int num_fields = taos_field_count(result); TAOS_FIELD *fields = taos_fetch_fields(result); - printf("fields: %d\n", num_fields); - printf("sql: %s, result:\n", sql); + fprintf(stdout, "query successfully, got %d fields, the sql is: %s.\n", num_fields, sql); + // fetch the records row by row while ((row = taos_fetch_row(result))) { - char temp[1024] = {0}; - if (taos_print_row(temp, row, fields, num_fields) < 0) { - printf("Failed to print row\n"); - break; - } - printf("%s\n", temp); + // Add your data processing logic here + rows++; } - printf("total rows: %d\n", rows); + fprintf(stdout, "total rows: %d\n", rows); taos_free_result(result); // close & clean From 562552bf303d55a566e18b94a70c751fbac52345 Mon Sep 17 00:00:00 2001 From: sheyanjie-qq <249478495@qq.com> Date: Fri, 16 Aug 2024 17:46:55 +0800 Subject: [PATCH 15/22] update rust sample code --- .../rust/nativeexample/examples/tmq.rs | 18 +++++++++++++++--- docs/examples/rust/restexample/examples/tmq.rs | 18 +++++++++++++++--- 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/docs/examples/rust/nativeexample/examples/tmq.rs b/docs/examples/rust/nativeexample/examples/tmq.rs index 2f8a9e5995..49580f81b7 100644 --- a/docs/examples/rust/nativeexample/examples/tmq.rs +++ b/docs/examples/rust/nativeexample/examples/tmq.rs @@ -86,7 +86,7 @@ async fn main() -> anyhow::Result<()> { match consumer.subscribe([topic]).await{ Ok(_) => println!("Subscribe topics successfully."), Err(err) => { - eprintln!("Failed to subscribe topic_meters, ErrMessage: {:?}", err); + eprintln!("Failed to subscribe topic: {}, groupId: {}, clientId: {}, ErrMessage: {:?}", topic, group_id, client_id, err); return Err(err.into()); } } @@ -164,7 +164,13 @@ async fn main() -> anyhow::Result<()> { // ANCHOR: seek_offset - let assignments = consumer.assignments().await.unwrap(); + let assignments = match consumer.assignments().await{ + Some(assignments) => assignments, + None => { + eprintln!("Failed to get assignments."); + return Err(anyhow::anyhow!("Failed to get assignments. topic: {}, groupId: {}, clientId: {}", topic, group_id, client_id)); + } + }; println!("assignments: {:?}", assignments); // seek offset @@ -200,7 +206,13 @@ async fn main() -> anyhow::Result<()> { } println!("Assignment seek to beginning successfully."); // after seek offset - let assignments = consumer.assignments().await.unwrap(); + let assignments = match consumer.assignments().await{ + Some(assignments) => assignments, + None => { + eprintln!("Failed to get assignments."); + return Err(anyhow::anyhow!("Failed to get assignments. topic: {}, groupId: {}, clientId: {}", topic, group_id, client_id)); + } + }; println!("After seek offset assignments: {:?}", assignments); // ANCHOR_END: seek_offset diff --git a/docs/examples/rust/restexample/examples/tmq.rs b/docs/examples/rust/restexample/examples/tmq.rs index 670ae0ca3c..86715d57cb 100644 --- a/docs/examples/rust/restexample/examples/tmq.rs +++ b/docs/examples/rust/restexample/examples/tmq.rs @@ -86,7 +86,7 @@ async fn main() -> anyhow::Result<()> { match consumer.subscribe([topic]).await{ Ok(_) => println!("Subscribe topics successfully."), Err(err) => { - eprintln!("Failed to subscribe topic_meters, ErrMessage: {:?}", err); + eprintln!("Failed to subscribe topic: {}, groupId: {}, clientId: {}, ErrMessage: {:?}", topic, group_id, client_id, err); return Err(err.into()); } } @@ -164,7 +164,13 @@ async fn main() -> anyhow::Result<()> { // ANCHOR: seek_offset - let assignments = consumer.assignments().await.unwrap(); + let assignments = match consumer.assignments().await{ + Some(assignments) => assignments, + None => { + eprintln!("Failed to get assignments."); + return Err(anyhow::anyhow!("Failed to get assignments. topic: {}, groupId: {}, clientId: {}", topic, group_id, client_id)); + } + }; println!("assignments: {:?}", assignments); // seek offset @@ -200,7 +206,13 @@ async fn main() -> anyhow::Result<()> { } println!("Assignment seek to beginning successfully."); // after seek offset - let assignments = consumer.assignments().await.unwrap(); + let assignments = match consumer.assignments().await{ + Some(assignments) => assignments, + None => { + eprintln!("Failed to get assignments."); + return Err(anyhow::anyhow!("Failed to get assignments. topic: {}, groupId: {}, clientId: {}", topic, group_id, client_id)); + } + }; println!("After seek offset assignments: {:?}", assignments); // ANCHOR_END: seek_offset From a9acc43550cdbe206375a47d15680f238fc7f50c Mon Sep 17 00:00:00 2001 From: Yaming Pei Date: Fri, 16 Aug 2024 18:25:02 +0800 Subject: [PATCH 16/22] python language sample program modification --- docs/examples/python/insert_native.py | 2 +- docs/examples/python/insert_rest.py | 2 +- docs/examples/python/insert_ws.py | 2 +- docs/examples/python/tmq_native.py | 66 +++++++++---------- docs/examples/python/tmq_websocket_example.py | 54 ++++++++------- 5 files changed, 65 insertions(+), 61 deletions(-) diff --git a/docs/examples/python/insert_native.py b/docs/examples/python/insert_native.py index ad7a8b85c2..19dafa3f23 100644 --- a/docs/examples/python/insert_native.py +++ b/docs/examples/python/insert_native.py @@ -21,7 +21,7 @@ try: print(f"Successfully inserted {affectedRows} rows to power.meters.") except Exception as err: - print(f"Failed to insert data to power.meters, ErrMessage:{err}") + print(f"Failed to insert data to power.meters, sql: {sql}, ErrMessage: {err}.") finally: if conn: conn.close() diff --git a/docs/examples/python/insert_rest.py b/docs/examples/python/insert_rest.py index 41fd70857f..526c3a6a69 100644 --- a/docs/examples/python/insert_rest.py +++ b/docs/examples/python/insert_rest.py @@ -20,7 +20,7 @@ try: print(f"Successfully inserted {affectedRows} rows to power.meters.") except Exception as err: - print(f"Failed to insert data to power.meters, ErrMessage:{err}") + print(f"Failed to insert data to power.meters, sql:{sql}, ErrMessage:{err}.") finally: if conn: conn.close() diff --git a/docs/examples/python/insert_ws.py b/docs/examples/python/insert_ws.py index 9c03b4857a..886dda1c10 100644 --- a/docs/examples/python/insert_ws.py +++ b/docs/examples/python/insert_ws.py @@ -21,7 +21,7 @@ try: print(f"Successfully inserted {affectedRows} rows to power.meters.") except Exception as err: - print(f"Failed to insert data to power.meters, ErrMessage:{err}") + print(f"Failed to insert data to power.meters, sql: {sql}, ErrMessage: {err}.") finally: if conn: conn.close() diff --git a/docs/examples/python/tmq_native.py b/docs/examples/python/tmq_native.py index 22a9b805bc..d4ccfda138 100644 --- a/docs/examples/python/tmq_native.py +++ b/docs/examples/python/tmq_native.py @@ -1,17 +1,24 @@ +#!/usr/bin/python3 import taos +db = "power" +topic = "topic_meters" +user = "root" +password = "taosdata" +host = "localhost" +port = 6030 +groupId = "group1" +clientId = "1" +tdConnWsScheme = "ws" +autoOffsetReset = "latest" +autoCommitState = "true" +autoCommitIntv = "1000" + + def prepareMeta(): conn = None try: - conn = taos.connect( - host="localhost", - user="root", - password="taosdata", - port=6030, - ) - - db = "power" - topic = "topic_meters" + conn = taos.connect(host=host, user=user, password=password, port=port) conn.execute(f"CREATE DATABASE IF NOT EXISTS {db}") # change database. same as execute "USE db" @@ -33,13 +40,13 @@ def prepareMeta(): power.d1001 USING power.meters (groupid, location) TAGS(2, 'California.SanFrancisco') VALUES (NOW + 1a, 10.30000, 219, 0.31000) (NOW + 2a, 12.60000, 218, 0.33000) (NOW + 3a, 12.30000, 221, 0.31000) - power.d1002 USING power.meters (groupid, location) TAGS(3, 'California.SanFrancisco') + power.d1002 USING power.meters (groupid, location) TAGS(3, 'California.SanFrancisco') VALUES (NOW + 1a, 10.30000, 218, 0.25000) """ affectedRows = conn.execute(sql) print(f"Inserted into {affectedRows} rows to power.meters successfully.") except Exception as err: - print(f"Prepare insert data error, ErrMessage:{err}") + print(f"Failed to prepareMeta, host: {host}:{port}, db: {db}, topic: {topic}, ErrMessage:{err}.") raise err finally: if conn: @@ -49,28 +56,24 @@ def prepareMeta(): from taos.tmq import Consumer def create_consumer(): - host = "localhost" - port = "6030" - groupId = "group1" - clientId = "1" try: consumer = Consumer( { "group.id": groupId, "client.id": clientId, - "td.connect.user": "root", - "td.connect.pass": "taosdata", - "enable.auto.commit": "true", - "auto.commit.interval.ms": "1000", - "auto.offset.reset": "latest", + "td.connect.user": user, + "td.connect.pass": password, + "enable.auto.commit": autoCommitState, + "auto.commit.interval.ms": autoCommitIntv, + "auto.offset.reset": autoOffsetReset, "td.connect.ip": host, - "td.connect.port": port, + "td.connect.port": str(port), } ) - print(f"Create consumer successfully, host: {host}:{port}, groupId: {groupId}, clientId: {clientId}"); + print(f"Create consumer successfully, host: {host}:{port}, groupId: {groupId}, clientId: {clientId}") return consumer except Exception as err: - print(f"Failed to create native consumer, host: {host}:{port}, ErrMessage:{err}"); + print(f"Failed to create native consumer, host: {host}:{port}, groupId: {groupId}, clientId: {clientId}, ErrMessage:{err}.") raise err # ANCHOR_END: create_consumer @@ -96,7 +99,7 @@ def subscribe(consumer): print(f"data: {data}") except Exception as err: - print(f"Failed to poll data, ErrMessage:{err}") + print(f"Failed to poll data, topic: {topic}, groupId: {groupId}, clientId: {clientId}, ErrMessage:{err}.") raise err @@ -123,7 +126,7 @@ def commit_offset(consumer): print("Commit offset manually successfully."); except Exception as err: - print(f"Failed to execute commit example, ErrMessage:{err}") + print(f"Failed to commit offset, topic: {topic}, groupId: {groupId}, clientId: {clientId}, ErrMessage:{err}.") raise err # ANCHOR_END: commit_offset @@ -136,9 +139,9 @@ def seek_offset(consumer): for partition in assignments: partition.offset = 0 consumer.seek(partition) - print(f"Assignment seek to beginning successfully"); + print(f"Assignment seek to beginning successfully.") except Exception as err: - print(f"Failed to execute seek example, ErrMessage:{err}") + print(f"Failed to seek offset, topic: {topic}, groupId: {groupId}, clientId: {clientId}, ErrMessage:{err}.") raise err # ANCHOR_END: assignment @@ -148,7 +151,7 @@ def unsubscribe(consumer): consumer.unsubscribe() print("Consumer unsubscribed successfully."); except Exception as err: - print(f"Failed to unsubscribe consumer. ErrMessage:{err}") + print(f"Failed to unsubscribe consumer. topic: {topic}, groupId: {groupId}, clientId: {clientId}, ErrMessage:{err}.") finally: if consumer: consumer.close() @@ -163,10 +166,7 @@ if __name__ == "__main__": subscribe(consumer) seek_offset(consumer) commit_offset(consumer) - consumer.unsubscribe() - print("Consumer unsubscribed successfully.") except Exception as err: - print(f"Failed to execute consumer example, ErrMessage:{err}") + print(f"Failed to execute consumer example, topic: {topic}, groupId: {groupId}, clientId: {clientId}, ErrMessage:{err}.") finally: - consumer.unsubscribe() - + unsubscribe(consumer); diff --git a/docs/examples/python/tmq_websocket_example.py b/docs/examples/python/tmq_websocket_example.py index 15441fbb41..793eb3c416 100644 --- a/docs/examples/python/tmq_websocket_example.py +++ b/docs/examples/python/tmq_websocket_example.py @@ -1,18 +1,26 @@ #!/usr/bin/python3 import taosws -topic = "topic_meters" +db = "power" +topic = "topic_meters" +user = "root" +password = "taosdata" +host = "localhost" +port = 6041 +groupId = "group1" +clientId = "1" +tdConnWsScheme = "ws" +autoOffsetReset = "latest" +autoCommitState = "true" +autoCommitIntv = "1000" + def prepareMeta(): conn = None try: - conn = taosws.connect(user="root", - password="taosdata", - host="localhost", - port=6041) + conn = taosws.connect(user=user, password=password, host=host, port=port) - db = "power" # create database rowsAffected = conn.execute(f"CREATE DATABASE IF NOT EXISTS {db}") assert rowsAffected == 0 @@ -51,7 +59,7 @@ def prepareMeta(): print(f"Inserted into {affectedRows} rows to power.meters successfully.") except Exception as err: - print(f"Failed to prepareMeta ErrMessage:{err}") + print(f"Failed to prepareMeta, host: {host}:{port}, db: {db}, topic: {topic}, ErrMessage:{err}.") raise err finally: if conn: @@ -59,26 +67,22 @@ def prepareMeta(): # ANCHOR: create_consumer -def create_consumer(): - host = "localhost" - port = 6041 - groupId = "group1" - clientId = "1" +def create_consumer(): try: consumer = taosws.Consumer(conf={ - "td.connect.websocket.scheme": "ws", + "td.connect.websocket.scheme": tdConnWsScheme, "group.id": groupId, "client.id": clientId, - "auto.offset.reset": "latest", + "auto.offset.reset": autoOffsetReset, "td.connect.ip": host, "td.connect.port": port, - "enable.auto.commit": "true", - "auto.commit.interval.ms": "1000", + "enable.auto.commit": autoCommitState, + "auto.commit.interval.ms": autoCommitIntv, }) - print(f"Create consumer successfully, host: {host}:{port}, groupId: {groupId}, clientId: {clientId}"); + print(f"Create consumer successfully, host: {host}:{port}, groupId: {groupId}, clientId: {clientId}."); return consumer; except Exception as err: - print(f"Failed to create websocket consumer, host: {host}:{port}, ErrMessage:{err}"); + print(f"Failed to create websocket consumer, host: {host}:{port}, groupId: {groupId}, clientId: {clientId}, ErrMessage:{err}."); raise err @@ -95,10 +99,10 @@ def seek_offset(consumer): print( f"vg_id: {assign.vg_id()}, offset: {assign.offset()}, begin: {assign.begin()}, end: {assign.end()}") consumer.seek(topic, assign.vg_id(), assign.begin()) - print("Assignment seek to beginning successfully"); + print("Assignment seek to beginning successfully.") except Exception as err: - print(f"Failed to execute seek example, ErrMessage:{err}") + print(f"Failed to seek offset, topic: {topic}, groupId: {groupId}, clientId: {clientId}, ErrMessage:{err}.") raise err # ANCHOR_END: assignment @@ -116,7 +120,7 @@ def subscribe(consumer): print(f"data: {row}") except Exception as err: - print(f"Failed to poll data, ErrMessage:{err}") + print(f"Failed to poll data, topic: {topic}, groupId: {groupId}, clientId: {clientId}, ErrMessage:{err}.") raise err @@ -134,10 +138,10 @@ def commit_offset(consumer): # after processing the data, commit the offset manually consumer.commit(records) - print("Commit offset manually successfully."); + print("Commit offset manually successfully.") except Exception as err: - print(f"Failed to execute commit example, ErrMessage:{err}") + print(f"Failed to commit offset, topic: {topic}, groupId: {groupId}, clientId: {clientId}, ErrMessage:{err}.") raise err @@ -150,7 +154,7 @@ def unsubscribe(consumer): consumer.unsubscribe() print("Consumer unsubscribed successfully."); except Exception as err: - print(f"Failed to unsubscribe consumer. ErrMessage:{err}") + print(f"Failed to unsubscribe consumer. topic: {topic}, groupId: {groupId}, clientId: {clientId}, ErrMessage:{err}.") finally: if consumer: consumer.close() @@ -167,6 +171,6 @@ if __name__ == "__main__": seek_offset(consumer) commit_offset(consumer) except Exception as err: - print(f"Failed to execute consumer example, ErrorMessage:{err}") + print(f"Failed to execute consumer example, topic: {topic}, groupId: {groupId}, clientId: {clientId}, ErrMessage:{err}.") finally: unsubscribe(consumer); From a49ac1f2ecacf20d96c8aac4f5a87c8aaf86ad2b Mon Sep 17 00:00:00 2001 From: sheyanjie-qq <249478495@qq.com> Date: Fri, 16 Aug 2024 20:03:30 +0800 Subject: [PATCH 17/22] update rust assignment --- docs/examples/rust/nativeexample/examples/tmq.rs | 10 ++++++---- docs/examples/rust/restexample/examples/tmq.rs | 10 ++++++---- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/docs/examples/rust/nativeexample/examples/tmq.rs b/docs/examples/rust/nativeexample/examples/tmq.rs index 49580f81b7..800b66e8fe 100644 --- a/docs/examples/rust/nativeexample/examples/tmq.rs +++ b/docs/examples/rust/nativeexample/examples/tmq.rs @@ -167,8 +167,9 @@ async fn main() -> anyhow::Result<()> { let assignments = match consumer.assignments().await{ Some(assignments) => assignments, None => { - eprintln!("Failed to get assignments."); - return Err(anyhow::anyhow!("Failed to get assignments. topic: {}, groupId: {}, clientId: {}", topic, group_id, client_id)); + let error_message = format!("Failed to get assignments. topic: {}, groupId: {}, clientId: {}", topic, group_id, client_id); + eprintln!("{}", error_message); + return Err(anyhow::anyhow!(error_message)); } }; println!("assignments: {:?}", assignments); @@ -209,8 +210,9 @@ async fn main() -> anyhow::Result<()> { let assignments = match consumer.assignments().await{ Some(assignments) => assignments, None => { - eprintln!("Failed to get assignments."); - return Err(anyhow::anyhow!("Failed to get assignments. topic: {}, groupId: {}, clientId: {}", topic, group_id, client_id)); + let error_message = format!("Failed to get assignments. topic: {}, groupId: {}, clientId: {}", topic, group_id, client_id); + eprintln!("{}", error_message); + return Err(anyhow::anyhow!(error_message)); } }; println!("After seek offset assignments: {:?}", assignments); diff --git a/docs/examples/rust/restexample/examples/tmq.rs b/docs/examples/rust/restexample/examples/tmq.rs index 86715d57cb..0a41025955 100644 --- a/docs/examples/rust/restexample/examples/tmq.rs +++ b/docs/examples/rust/restexample/examples/tmq.rs @@ -167,8 +167,9 @@ async fn main() -> anyhow::Result<()> { let assignments = match consumer.assignments().await{ Some(assignments) => assignments, None => { - eprintln!("Failed to get assignments."); - return Err(anyhow::anyhow!("Failed to get assignments. topic: {}, groupId: {}, clientId: {}", topic, group_id, client_id)); + let error_message = format!("Failed to get assignments. topic: {}, groupId: {}, clientId: {}", topic, group_id, client_id); + eprintln!("{}", error_message); + return Err(anyhow::anyhow!(error_message)); } }; println!("assignments: {:?}", assignments); @@ -209,8 +210,9 @@ async fn main() -> anyhow::Result<()> { let assignments = match consumer.assignments().await{ Some(assignments) => assignments, None => { - eprintln!("Failed to get assignments."); - return Err(anyhow::anyhow!("Failed to get assignments. topic: {}, groupId: {}, clientId: {}", topic, group_id, client_id)); + let error_message = format!("Failed to get assignments. topic: {}, groupId: {}, clientId: {}", topic, group_id, client_id); + eprintln!("{}", error_message); + return Err(anyhow::anyhow!(error_message)); } }; println!("After seek offset assignments: {:?}", assignments); From 5011a05e11c7f49d5c09b6d3745d1d08d05f0ce0 Mon Sep 17 00:00:00 2001 From: Yaming Pei Date: Fri, 16 Aug 2024 20:11:18 +0800 Subject: [PATCH 18/22] c language sample tmq program optimization --- docs/examples/c/tmq_demo.c | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/docs/examples/c/tmq_demo.c b/docs/examples/c/tmq_demo.c index 9deff9add5..b16245d484 100644 --- a/docs/examples/c/tmq_demo.c +++ b/docs/examples/c/tmq_demo.c @@ -314,7 +314,8 @@ tmq_list_t* build_topic_list() { if (code) { // if failed, destroy the list and return NULL tmq_list_destroy(topicList); - fprintf(stderr, "Failed to create topic_list, ErrCode: 0x%x, ErrMessage: %s.\n", code, tmq_err2str(code)); + fprintf(stderr, "Failed to create topic_list, topic: %s, groupId: %s, clientId: %s, ErrCode: 0x%x, ErrMessage: %s.\n", + topic_name, config.group_id, config.client_id, code, tmq_err2str(code)); return NULL; } // if success, return the list @@ -347,7 +348,7 @@ void basic_consume_loop(tmq_t* tmq) { } // print the result: total messages and total rows consumed - fprintf(stderr, "%d msg consumed, include %d rows\n", msgCnt, totalRows); + fprintf(stdout, "%d msg consumed, include %d rows\n", msgCnt, totalRows); } // ANCHOR_END: basic_consume_loop @@ -359,7 +360,8 @@ void consume_repeatly(tmq_t* tmq) { // get the topic assignment int32_t code = tmq_get_topic_assignment(tmq, topic_name, &pAssign, &numOfAssignment); if (code != 0 || pAssign == NULL || numOfAssignment == 0) { - fprintf(stderr, "Failed to get assignment, ErrCode: 0x%x, ErrMessage: %s.\n", code, tmq_err2str(code)); + fprintf(stderr, "Failed to get assignment, topic: %s, groupId: %s, clientId: %s, ErrCode: 0x%x, ErrMessage: %s.\n", + topic_name, config.group_id, config.client_id, code, tmq_err2str(code)); return; } @@ -419,7 +421,7 @@ void manual_commit(tmq_t* tmq) { } // print the result: total messages and total rows consumed - fprintf(stderr, "%d msg consumed, include %d rows.\n", msgCnt, totalRows); + fprintf(stdout, "%d msg consumed, include %d rows.\n", msgCnt, totalRows); } // ANCHOR_END: manual_commit @@ -459,12 +461,14 @@ int main(int argc, char* argv[]) { // ANCHOR: subscribe_3 tmq_list_t* topic_list = build_topic_list(); if (NULL == topic_list) { - fprintf(stderr, "Failed to create topic_list.\n"); + fprintf(stderr, "Failed to create topic_list, topic: %s, groupId: %s, clientId: %s.\n", + topic_name, config.group_id, config.client_id); return -1; } if ((code = tmq_subscribe(tmq, topic_list))) { - fprintf(stderr, "Failed to subscribe topic_list, ErrCode: 0x%x, ErrMessage: %s.\n", code, tmq_err2str(code)); + fprintf(stderr, "Failed to subscribe topic_list, topic: %s, groupId: %s, clientId: %s, ErrCode: 0x%x, ErrMessage: %s.\n", + topic_name, config.group_id, config.client_id, code, tmq_err2str(code)); } else { fprintf(stdout, "Subscribe topics successfully.\n"); } @@ -485,15 +489,16 @@ int main(int argc, char* argv[]) { fprintf(stderr, "Failed to unsubscribe consumer, topic: %s, groupId: %s, clientId: %s, ErrCode: 0x%x, ErrMessage: %s.\n", topic_name, config.group_id, config.client_id, code, tmq_err2str(code)); } else { - fprintf(stderr, "Consumer unsubscribed successfully.\n"); + fprintf(stdout, "Consumer unsubscribed successfully.\n"); } // close the consumer code = tmq_consumer_close(tmq); if (code) { - fprintf(stderr, "Failed to close consumer: %s.\n", tmq_err2str(code)); + fprintf(stderr, "Failed to close consumer, topic: %s, groupId: %s, clientId: %s, ErrCode: 0x%x, ErrMessage: %s.\n", + topic_name, config.group_id, config.client_id, code, tmq_err2str(code)); } else { - fprintf(stderr, "Consumer closed successfully.\n"); + fprintf(stdout, "Consumer closed successfully.\n"); } // ANCHOR_END: unsubscribe_and_close From c1e5a6e6f9c297fda508f2e7136ed802eb7042e2 Mon Sep 17 00:00:00 2001 From: Yaming Pei Date: Fri, 16 Aug 2024 20:36:40 +0800 Subject: [PATCH 19/22] python language sample program modification --- docs/examples/python/tmq_websocket_example.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/examples/python/tmq_websocket_example.py b/docs/examples/python/tmq_websocket_example.py index 793eb3c416..c9c7924661 100644 --- a/docs/examples/python/tmq_websocket_example.py +++ b/docs/examples/python/tmq_websocket_example.py @@ -173,4 +173,4 @@ if __name__ == "__main__": except Exception as err: print(f"Failed to execute consumer example, topic: {topic}, groupId: {groupId}, clientId: {clientId}, ErrMessage:{err}.") finally: - unsubscribe(consumer); + unsubscribe(consumer) From 42c7b6ca33efdb568866609faf373da03e063df2 Mon Sep 17 00:00:00 2001 From: Yaming Pei Date: Sat, 17 Aug 2024 11:42:14 +0800 Subject: [PATCH 20/22] c language sample program modification --- docs/examples/c/tmq_demo.c | 5 ++--- docs/examples/c/with_reqid_demo.c | 1 - 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/docs/examples/c/tmq_demo.c b/docs/examples/c/tmq_demo.c index b16245d484..18eef02098 100644 --- a/docs/examples/c/tmq_demo.c +++ b/docs/examples/c/tmq_demo.c @@ -92,7 +92,6 @@ void* prepare_data(void* arg) { // ANCHOR: msg_process int32_t msg_process(TAOS_RES* msg) { - char buf[1024]; // buf to store the row content int32_t rows = 0; const char* topicName = tmq_get_topic_name(msg); const char* dbName = tmq_get_db_name(msg); @@ -371,8 +370,8 @@ void consume_repeatly(tmq_t* tmq) { code = tmq_offset_seek(tmq, topic_name, p->vgId, p->begin); if (code != 0) { - fprintf(stderr, "Failed to seek offset, topic: %s, groupId: %s, clientId: %s, ErrCode: 0x%x, ErrMessage: %s.\n", - topic_name, config.group_id, config.client_id, code, tmq_err2str(code)); + fprintf(stderr, "Failed to seek offset, topic: %s, groupId: %s, clientId: %s, vgId: %d, ErrCode: 0x%x, ErrMessage: %s.\n", + topic_name, config.group_id, config.client_id, p->vgId, code, tmq_err2str(code)); break; } } diff --git a/docs/examples/c/with_reqid_demo.c b/docs/examples/c/with_reqid_demo.c index 8942077f67..1a1a53acc6 100644 --- a/docs/examples/c/with_reqid_demo.c +++ b/docs/examples/c/with_reqid_demo.c @@ -57,7 +57,6 @@ static int DemoWithReqId() { fprintf(stdout, "query successfully, got %d fields, the sql is: %s.\n", num_fields, sql); - // fetch the records row by row while ((row = taos_fetch_row(result))) { // Add your data processing logic here From a360240e780ec9b08ff007609e8cebff8a8c707e Mon Sep 17 00:00:00 2001 From: sheyanjie-qq <249478495@qq.com> Date: Sat, 17 Aug 2024 17:40:44 +0800 Subject: [PATCH 21/22] update node log --- .../node/websocketexample/line_example.js | 2 +- .../examples/node/websocketexample/sql_example.js | 8 ++++---- .../node/websocketexample/stmt_example.js | 2 +- .../examples/node/websocketexample/tmq_example.js | 15 ++++++++++----- .../node/websocketexample/tmq_seek_example.js | 13 +++++++++---- 5 files changed, 25 insertions(+), 15 deletions(-) diff --git a/docs/examples/node/websocketexample/line_example.js b/docs/examples/node/websocketexample/line_example.js index 4fc5042f5a..ac3083d358 100644 --- a/docs/examples/node/websocketexample/line_example.js +++ b/docs/examples/node/websocketexample/line_example.js @@ -28,7 +28,7 @@ async function test() { console.log("Inserted data with schemaless successfully.") } catch (err) { - console.error("Failed to insert data with schemaless, ErrCode: " + err.code + ", ErrMessage: " + err.message); + console.error(`Failed to insert data with schemaless, ErrCode: ${err.code}, ErrMessage: ${err.message}`); } finally { if (wsRows) { diff --git a/docs/examples/node/websocketexample/sql_example.js b/docs/examples/node/websocketexample/sql_example.js index 8ef4dcb831..1f756c8a09 100644 --- a/docs/examples/node/websocketexample/sql_example.js +++ b/docs/examples/node/websocketexample/sql_example.js @@ -35,7 +35,7 @@ async function createDbAndTable() { console.log("Create stable power.meters successfully"); } catch (err) { - console.error("Failed to create database power or stable meters, ErrCode: " + err.code + ", ErrMessage: " + err.message); + console.error(`Failed to create database power or stable meters, ErrCode: ${err.code}, ErrMessage: ${err.message}`); } finally { if (wsSql) { await wsSql.close(); @@ -62,7 +62,7 @@ async function insertData() { taosResult = await wsSql.exec(insertQuery); console.log("Successfully inserted " + taosResult.getAffectRows() + " rows to power.meters."); } catch (err) { - console.error("Failed to insert data to power.meters, ErrCode: " + err.code + ", ErrMessage: " + err.message); + console.error(`Failed to insert data to power.meters, sql: ${insertQuery}, ErrCode: ${err.code}, ErrMessage: ${err.message}`); } finally { if (wsSql) { await wsSql.close(); @@ -85,7 +85,7 @@ async function queryData() { } } catch (err) { - console.error("Failed to query data from power.meters, sql: " + sql + ", ErrCode:" + err.code + ", ErrMessage: " + err.message); + console.error(`Failed to query data from power.meters, sql: ${sql}, ErrCode: ${err.code}, ErrMessage: ${err.message}`); } finally { if (wsRows) { @@ -112,7 +112,7 @@ async function sqlWithReqid() { } } catch (err) { - console.error("Failed to execute sql with reqId: " + reqId + ", ErrCode: " + err.code + ", ErrMessage: " + err.message); + console.error(`Failed to query data from power.meters, reqId: ${reqId}, ErrCode: ${err.code}, ErrMessage: ${err.message}`); } finally { if (wsRows) { diff --git a/docs/examples/node/websocketexample/stmt_example.js b/docs/examples/node/websocketexample/stmt_example.js index 6ca4959c48..e3bb3c4dda 100644 --- a/docs/examples/node/websocketexample/stmt_example.js +++ b/docs/examples/node/websocketexample/stmt_example.js @@ -59,7 +59,7 @@ async function prepare() { } } catch (err) { - console.error("Failed to insert to table meters using stmt, ErrCode: " + err.code + ", ErrMessage: " + err.message); + console.error(`Failed to insert to table meters using stmt, ErrCode: ${err.code}, ErrMessage: ${err.message}`); } finally { if (stmt) { diff --git a/docs/examples/node/websocketexample/tmq_example.js b/docs/examples/node/websocketexample/tmq_example.js index fc9d2889e0..5097402e6a 100644 --- a/docs/examples/node/websocketexample/tmq_example.js +++ b/docs/examples/node/websocketexample/tmq_example.js @@ -3,12 +3,16 @@ const taos = require("@tdengine/websocket"); // ANCHOR: create_consumer const db = 'power'; const stable = 'meters'; -const topics = ['power_meters_topic']; const url = 'ws://localhost:6041'; +const topic = 'topic_meters' +const topics = [topic]; +const groupId = "group1"; +const clientId = "client1"; + async function createConsumer() { let groupId = "group1"; - let clientId = "1"; + let clientId = "client1"; let configMap = new Map([ [taos.TMQConstants.GROUP_ID, groupId], [taos.TMQConstants.CLIENT_ID, clientId], @@ -24,7 +28,7 @@ async function createConsumer() { console.log(`Create consumer successfully, host: ${url}, groupId: ${groupId}, clientId: ${clientId}`) return conn; } catch (err) { - console.log("Failed to create websocket consumer, ErrCode:" + err.code + ", ErrMessage: " + err.message); + console.error(`Failed to create websocket consumer, topic: ${topic}, groupId: ${groupId}, clientId: ${clientId}, ErrCode: ${err.code}, ErrMessage: ${err.message}`); throw err; } @@ -60,13 +64,14 @@ async function subscribe(consumer) { for (let i = 0; i < 50; i++) { let res = await consumer.poll(100); for (let [key, value] of res) { + // Add your data processing logic here console.log(`data: ${key} ${value}`); } await consumer.commit(); console.log("Commit offset manually successfully."); } } catch (err) { - console.error("Failed to poll data, ErrCode: " + err.code + ", ErrMessage: " + err.message); + console.error(`Failed to poll data, topic: ${topic}, groupId: ${groupId}, clientId: ${clientId}, ErrCode: ${err.code}, ErrMessage: ${err.message}`); throw err; } // ANCHOR_END: commit @@ -83,7 +88,7 @@ async function test() { console.log("Consumer unsubscribed successfully."); } catch (err) { - console.error("Failed to unsubscribe consumer, ErrCode: " + err.code + ", ErrMessage: " + err.message); + console.error(`Failed to unsubscribe consumer, topic: ${topic}, groupId: ${groupId}, clientId: ${clientId}, ErrCode: ${err.code}, ErrMessage: ${err.message}`); } finally { if (consumer) { diff --git a/docs/examples/node/websocketexample/tmq_seek_example.js b/docs/examples/node/websocketexample/tmq_seek_example.js index 259614d5db..b2bd569d92 100644 --- a/docs/examples/node/websocketexample/tmq_seek_example.js +++ b/docs/examples/node/websocketexample/tmq_seek_example.js @@ -2,7 +2,11 @@ const taos = require("@tdengine/websocket"); const db = 'power'; const stable = 'meters'; -const topics = ['power_meters_topic']; +const topic = 'topic_meters' +const topics = [topic]; +const groupId = "group1"; +const clientId = "client1"; + // ANCHOR: create_consumer async function createConsumer() { @@ -19,7 +23,7 @@ async function createConsumer() { try { return await taos.tmqConnect(configMap); } catch (err) { - console.log(err); + console.error(err); throw err; } @@ -55,11 +59,12 @@ async function subscribe(consumer) { for (let i = 0; i < 50; i++) { let res = await consumer.poll(100); for (let [key, value] of res) { + // Add your data processing logic here console.log(`data: ${key} ${value}`); } } } catch (err) { - console.error("Failed to poll data, ErrCode: " + err.code + ", ErrMessage: " + err.message); + console.error(`Failed to poll data, topic: ${topic}, groupId: ${groupId}, clientId: ${clientId}, ErrCode: ${err.code}, ErrMessage: ${err.message}`); throw err; } @@ -83,7 +88,7 @@ async function test() { console.log("Assignment seek to beginning successfully"); } catch (err) { - console.error("Failed to execute seek example, ErrCode: " + err.code + ", ErrMessage: " + err.message); + console.error(`Failed to seek offset, topic: ${topic}, groupId: ${groupId}, clientId: ${clientId}, ErrCode: ${err.code}, ErrMessage: ${err.message}`); } finally { if (consumer) { From 7355967c4102fa0ef9f4b1cb9cdaaf21d7eda946 Mon Sep 17 00:00:00 2001 From: sheyanjie-qq <249478495@qq.com> Date: Sat, 17 Aug 2024 18:02:04 +0800 Subject: [PATCH 22/22] fix typo --- docs/examples/node/websocketexample/sql_example.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/examples/node/websocketexample/sql_example.js b/docs/examples/node/websocketexample/sql_example.js index 1f756c8a09..5dc8ba6021 100644 --- a/docs/examples/node/websocketexample/sql_example.js +++ b/docs/examples/node/websocketexample/sql_example.js @@ -13,7 +13,7 @@ async function createConnect() { console.log("Connected to " + dsn + " successfully."); return conn; } catch (err) { - console.log("Failed to connect to " + dns + ", ErrCode: " + err.code + ", ErrMessage: " + err.message); + console.log("Failed to connect to " + dsn + ", ErrCode: " + err.code + ", ErrMessage: " + err.message); throw err; }