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
}