C/C++ Connector

C/C++ developers can use TDengine’s client driver and the C/C++ connector, to develop their applications to connect to TDengine clusters for data writing, querying, and other functions. To use the C/C++ connector you must include the TDengine header file taos.h, which lists the function prototypes of the provided APIs. The application also needs to link to the corresponding dynamic libraries on the platform where it is located.

  1. #include <taos.h>

After TDengine server or client installation, taos.h is located at

  • Linux:/usr/local/taos/include
  • Windows:C:\TDengine\include
  • macOS:/usr/local/include

The dynamic libraries for the TDengine client driver are located in.

  • Linux: /usr/local/taos/driver/libtaos.so
  • Windows: C:\TDengine\taos.dll
  • macOS: /usr/local/lib/libtaos.dylib

Supported platforms

Please refer to list of supported platforms

Supported versions

The version number of the TDengine client driver and the version number of the TDengine server should be same. A lower version of the client driver is compatible with a higher version of the server, if the first three version numbers are the same (i.e., only the fourth version number is different). For e.g. if the client version is x.y.z.1 and the server version is x.y.z.2 the client and server are compatible. But in general we do not recommend using a lower client version with a newer server version. It is also strongly discouraged to use a higher version of the client driver to access a lower version of the TDengine server.

Installation Steps

Please refer to the Installation Steps for TDengine client driver installation

Establishing a connection

The basic process of accessing a TDengine cluster using the client driver is to establish a connection, query and write data, close the connection, and clear the resource.

The following is sample code for establishing a connection, which omits the query and writing sections and shows how to establish a connection, close a connection, and clear a resource.

  1. TAOS *taos = taos_connect("localhost:6030", "root", "taosdata", NULL, 0);
  2. if (taos == NULL) {
  3. printf("failed to connect to server, reason:%s\n", "null taos" /*taos_errstr(taos)*/);
  4. exit(1);
  5. }
  6. /* put your code here for read and write */
  7. taos_close(taos);
  8. taos_cleanup();

In the above example code, taos_connect() establishes a connection to port 6030 on the host where the client application is located, taos_close() closes the current connection, and taos_cleanup() clears the resources requested and used by the client driver.

C/C++ - 图1note
  • If not specified, when the return value of the API is an integer, 0 means success. All others are error codes representing the reason for failure. When the return value is a pointer, NULL means failure.
  • All error codes and their corresponding causes are described in the taoserror.h file.

Sample program

This section shows sample code for standard access methods to TDengine clusters using the client driver.

Synchronous query example

Synchronous query

  1. /*
  2. * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
  3. *
  4. * This program is free software: you can use, redistribute, and/or modify
  5. * it under the terms of the GNU Affero General Public License, version 3
  6. * or later ("AGPL"), as published by the Free Software Foundation.
  7. *
  8. * This program is distributed in the hope that it will be useful, but WITHOUT
  9. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. * FITNESS FOR A PARTICULAR PURPOSE.
  11. *
  12. * You should have received a copy of the GNU Affero General Public License
  13. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. // TAOS standard API example. The same syntax as MySQL, but only a subset
  16. // to compile: gcc -o demo demo.c -ltaos
  17. #include <inttypes.h>
  18. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include "taos.h" // TAOS header file
  22. static void queryDB(TAOS *taos, char *command) {
  23. int i;
  24. TAOS_RES *pSql = NULL;
  25. int32_t code = -1;
  26. for (i = 0; i < 5; i++) {
  27. if (NULL != pSql) {
  28. taos_free_result(pSql);
  29. pSql = NULL;
  30. }
  31. pSql = taos_query(taos, command);
  32. code = taos_errno(pSql);
  33. if (0 == code) {
  34. break;
  35. }
  36. }
  37. if (code != 0) {
  38. fprintf(stderr, "Failed to run %s, reason: %s\n", command, taos_errstr(pSql));
  39. taos_free_result(pSql);
  40. taos_close(taos);
  41. exit(EXIT_FAILURE);
  42. }
  43. taos_free_result(pSql);
  44. }
  45. void Test(TAOS *taos, char *qstr, int i);
  46. int main(int argc, char *argv[]) {
  47. char qstr[1024];
  48. // connect to server
  49. if (argc < 2) {
  50. printf("please input server-ip \n");
  51. return 0;
  52. }
  53. TAOS *taos = taos_connect(argv[1], "root", "taosdata", NULL, 0);
  54. if (taos == NULL) {
  55. printf("failed to connect to server, reason:%s\n", "null taos"/*taos_errstr(taos)*/);
  56. exit(1);
  57. }
  58. for (int i = 0; i < 100; i++) {
  59. Test(taos, qstr, i);
  60. }
  61. taos_close(taos);
  62. taos_cleanup();
  63. }
  64. void Test(TAOS *taos, char *qstr, int index) {
  65. printf("==================test at %d\n================================", index);
  66. queryDB(taos, "drop database if exists demo");
  67. queryDB(taos, "create database demo");
  68. TAOS_RES *result;
  69. queryDB(taos, "use demo");
  70. queryDB(taos, "create table m1 (ts timestamp, ti tinyint, si smallint, i int, bi bigint, f float, d double, b binary(10))");
  71. printf("success to create table\n");
  72. int i = 0;
  73. for (i = 0; i < 10; ++i) {
  74. sprintf(qstr, "insert into m1 values (%" PRId64 ", %d, %d, %d, %d, %f, %lf, '%s')", (uint64_t)(1546300800000 + i * 1000), i, i, i, i*10000000, i*1.0, i*2.0, "hello");
  75. printf("qstr: %s\n", qstr);
  76. // note: how do you wanna do if taos_query returns non-NULL
  77. // if (taos_query(taos, qstr)) {
  78. // printf("insert row: %i, reason:%s\n", i, taos_errstr(taos));
  79. // }
  80. TAOS_RES *result1 = taos_query(taos, qstr);
  81. if (result1 == NULL || taos_errno(result1) != 0) {
  82. printf("failed to insert row, reason:%s\n", taos_errstr(result1));
  83. taos_free_result(result1);
  84. exit(1);
  85. } else {
  86. printf("insert row: %i\n", i);
  87. }
  88. taos_free_result(result1);
  89. }
  90. printf("success to insert rows, total %d rows\n", i);
  91. // query the records
  92. sprintf(qstr, "SELECT * FROM m1");
  93. result = taos_query(taos, qstr);
  94. if (result == NULL || taos_errno(result) != 0) {
  95. printf("failed to select, reason:%s\n", taos_errstr(result));
  96. taos_free_result(result);
  97. exit(1);
  98. }
  99. TAOS_ROW row;
  100. int rows = 0;
  101. int num_fields = taos_field_count(result);
  102. TAOS_FIELD *fields = taos_fetch_fields(result);
  103. printf("num_fields = %d\n", num_fields);
  104. printf("select * from table, result:\n");
  105. // fetch the records row by row
  106. while ((row = taos_fetch_row(result))) {
  107. char temp[1024] = {0};
  108. rows++;
  109. taos_print_row(temp, row, fields, num_fields);
  110. printf("%s\n", temp);
  111. }
  112. taos_free_result(result);
  113. printf("====demo end====\n\n");
  114. }

view source code

Asynchronous query example

Asynchronous queries

  1. /*
  2. * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
  3. *
  4. * This program is free software: you can use, redistribute, and/or modify
  5. * it under the terms of the GNU Affero General Public License, version 3
  6. * or later ("AGPL"), as published by the Free Software Foundation.
  7. *
  8. * This program is distributed in the hope that it will be useful, but WITHOUT
  9. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. * FITNESS FOR A PARTICULAR PURPOSE.
  11. *
  12. * You should have received a copy of the GNU Affero General Public License
  13. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. // TAOS asynchronous API example
  16. // this example opens multiple tables, insert/retrieve multiple tables
  17. // it is used by TAOS internally for one performance testing
  18. // to compiple: gcc -o asyncdemo asyncdemo.c -ltaos
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <sys/time.h>
  22. #include <unistd.h>
  23. #include <string.h>
  24. #include <inttypes.h>
  25. #include "taos.h"
  26. int points = 5;
  27. int numOfTables = 3;
  28. int tablesInsertProcessed = 0;
  29. int tablesSelectProcessed = 0;
  30. int64_t st, et;
  31. typedef struct {
  32. int id;
  33. TAOS *taos;
  34. char name[32];
  35. time_t timeStamp;
  36. int value;
  37. int rowsInserted;
  38. int rowsTried;
  39. int rowsRetrieved;
  40. } STable;
  41. void taos_insert_call_back(void *param, TAOS_RES *tres, int code);
  42. void taos_select_call_back(void *param, TAOS_RES *tres, int code);
  43. void shellPrintError(TAOS *taos);
  44. static void queryDB(TAOS *taos, char *command) {
  45. int i;
  46. TAOS_RES *pSql = NULL;
  47. int32_t code = -1;
  48. for (i = 0; i < 5; i++) {
  49. if (NULL != pSql) {
  50. taos_free_result(pSql);
  51. pSql = NULL;
  52. }
  53. pSql = taos_query(taos, command);
  54. code = taos_errno(pSql);
  55. if (0 == code) {
  56. break;
  57. }
  58. }
  59. if (code != 0) {
  60. fprintf(stderr, "Failed to run %s, reason: %s\n", command, taos_errstr(pSql));
  61. taos_free_result(pSql);
  62. taos_close(taos);
  63. taos_cleanup();
  64. exit(EXIT_FAILURE);
  65. }
  66. taos_free_result(pSql);
  67. }
  68. int main(int argc, char *argv[])
  69. {
  70. TAOS *taos;
  71. struct timeval systemTime;
  72. int i;
  73. char sql[1024] = { 0 };
  74. char prefix[20] = { 0 };
  75. char db[128] = { 0 };
  76. STable *tableList;
  77. if (argc != 5) {
  78. printf("usage: %s server-ip dbname rowsPerTable numOfTables\n", argv[0]);
  79. exit(0);
  80. }
  81. // a simple way to parse input parameters
  82. if (argc >= 3) strcpy(db, argv[2]);
  83. if (argc >= 4) points = atoi(argv[3]);
  84. if (argc >= 5) numOfTables = atoi(argv[4]);
  85. size_t size = sizeof(STable) * (size_t)numOfTables;
  86. tableList = (STable *)malloc(size);
  87. memset(tableList, 0, size);
  88. taos = taos_connect(argv[1], "root", "taosdata", NULL, 0);
  89. if (taos == NULL)
  90. shellPrintError(taos);
  91. printf("success to connect to server\n");
  92. sprintf(sql, "drop database if exists %s", db);
  93. queryDB(taos, sql);
  94. sprintf(sql, "create database %s", db);
  95. queryDB(taos, sql);
  96. sprintf(sql, "use %s", db);
  97. queryDB(taos, sql);
  98. strcpy(prefix, "asytbl_");
  99. for (i = 0; i < numOfTables; ++i) {
  100. tableList[i].id = i;
  101. tableList[i].taos = taos;
  102. sprintf(tableList[i].name, "%s%d", prefix, i);
  103. sprintf(sql, "create table %s%d (ts timestamp, volume bigint)", prefix, i);
  104. queryDB(taos, sql);
  105. }
  106. gettimeofday(&systemTime, NULL);
  107. for (i = 0; i < numOfTables; ++i)
  108. tableList[i].timeStamp = (time_t)(systemTime.tv_sec) * 1000 + systemTime.tv_usec / 1000;
  109. printf("success to create tables, press any key to insert\n");
  110. getchar();
  111. printf("start to insert...\n");
  112. gettimeofday(&systemTime, NULL);
  113. st = systemTime.tv_sec * 1000000 + systemTime.tv_usec;
  114. tablesInsertProcessed = 0;
  115. tablesSelectProcessed = 0;
  116. for (i = 0; i<numOfTables; ++i) {
  117. // insert records in asynchronous API
  118. sprintf(sql, "insert into %s values(%ld, 0)", tableList[i].name, 1546300800000 + i);
  119. taos_query_a(taos, sql, taos_insert_call_back, (void *)(tableList + i));
  120. }
  121. printf("once insert finished, presse any key to query\n");
  122. getchar();
  123. while(1) {
  124. if (tablesInsertProcessed < numOfTables) {
  125. printf("wait for process finished\n");
  126. sleep(1);
  127. continue;
  128. }
  129. break;
  130. }
  131. printf("start to query...\n");
  132. gettimeofday(&systemTime, NULL);
  133. st = systemTime.tv_sec * 1000000 + systemTime.tv_usec;
  134. for (i = 0; i < numOfTables; ++i) {
  135. // select records in asynchronous API
  136. sprintf(sql, "select * from %s", tableList[i].name);
  137. taos_query_a(taos, sql, taos_select_call_back, (void *)(tableList + i));
  138. }
  139. printf("\nonce finished, press any key to exit\n");
  140. getchar();
  141. while(1) {
  142. if (tablesSelectProcessed < numOfTables) {
  143. printf("wait for process finished\n");
  144. sleep(1);
  145. continue;
  146. }
  147. break;
  148. }
  149. for (i = 0; i<numOfTables; ++i) {
  150. printf("%s inserted:%d retrieved:%d\n", tableList[i].name, tableList[i].rowsInserted, tableList[i].rowsRetrieved);
  151. }
  152. taos_close(taos);
  153. free(tableList);
  154. printf("==== async demo end====\n");
  155. printf("\n");
  156. return 0;
  157. }
  158. void shellPrintError(TAOS *con)
  159. {
  160. fprintf(stderr, "TDengine error: %s\n", taos_errstr(con));
  161. taos_close(con);
  162. taos_cleanup();
  163. exit(1);
  164. }
  165. void taos_insert_call_back(void *param, TAOS_RES *tres, int code)
  166. {
  167. STable *pTable = (STable *)param;
  168. struct timeval systemTime;
  169. char sql[128];
  170. pTable->rowsTried++;
  171. if (code < 0) {
  172. printf("%s insert failed, code:%d, rows:%d\n", pTable->name, code, pTable->rowsTried);
  173. }
  174. else if (code == 0) {
  175. printf("%s not inserted\n", pTable->name);
  176. }
  177. else {
  178. pTable->rowsInserted++;
  179. }
  180. if (pTable->rowsTried < points) {
  181. // for this demo, insert another record
  182. sprintf(sql, "insert into %s values(%ld, %d)", pTable->name, 1546300800000+pTable->rowsTried*1000, pTable->rowsTried);
  183. taos_query_a(pTable->taos, sql, taos_insert_call_back, (void *)pTable);
  184. }
  185. else {
  186. printf("%d rows data are inserted into %s\n", points, pTable->name);
  187. tablesInsertProcessed++;
  188. if (tablesInsertProcessed >= numOfTables) {
  189. gettimeofday(&systemTime, NULL);
  190. et = systemTime.tv_sec * 1000000 + systemTime.tv_usec;
  191. printf("%" PRId64 " mseconds to insert %d data points\n", (et - st) / 1000, points*numOfTables);
  192. }
  193. }
  194. taos_free_result(tres);
  195. }
  196. void taos_retrieve_call_back(void *param, TAOS_RES *tres, int numOfRows)
  197. {
  198. STable *pTable = (STable *)param;
  199. struct timeval systemTime;
  200. if (numOfRows > 0) {
  201. for (int i = 0; i<numOfRows; ++i) {
  202. // synchronous API to retrieve a row from batch of records
  203. /*TAOS_ROW row = */(void)taos_fetch_row(tres);
  204. // process row
  205. }
  206. pTable->rowsRetrieved += numOfRows;
  207. // retrieve next batch of rows
  208. taos_fetch_rows_a(tres, taos_retrieve_call_back, pTable);
  209. }
  210. else {
  211. if (numOfRows < 0)
  212. printf("%s retrieve failed, code:%d\n", pTable->name, numOfRows);
  213. //taos_free_result(tres);
  214. printf("%d rows data retrieved from %s\n", pTable->rowsRetrieved, pTable->name);
  215. tablesSelectProcessed++;
  216. if (tablesSelectProcessed >= numOfTables) {
  217. gettimeofday(&systemTime, NULL);
  218. et = systemTime.tv_sec * 1000000 + systemTime.tv_usec;
  219. printf("%" PRId64 " mseconds to query %d data rows\n", (et - st) / 1000, points * numOfTables);
  220. }
  221. taos_free_result(tres);
  222. }
  223. }
  224. void taos_select_call_back(void *param, TAOS_RES *tres, int code)
  225. {
  226. STable *pTable = (STable *)param;
  227. if (code == 0 && tres) {
  228. // asynchronous API to fetch a batch of records
  229. taos_fetch_rows_a(tres, taos_retrieve_call_back, pTable);
  230. }
  231. else {
  232. printf("%s select failed, code:%d\n", pTable->name, code);
  233. taos_free_result(tres);
  234. taos_cleanup();
  235. exit(1);
  236. }
  237. }

view source code

Parameter binding example

Parameter Binding

  1. // TAOS standard API example. The same syntax as MySQL, but only a subet
  2. // to compile: gcc -o prepare prepare.c -ltaos
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include "taos.h"
  7. void taosMsleep(int mseconds);
  8. int main(int argc, char *argv[])
  9. {
  10. TAOS *taos;
  11. TAOS_RES *result;
  12. int code;
  13. TAOS_STMT *stmt;
  14. // connect to server
  15. if (argc < 2) {
  16. printf("please input server ip \n");
  17. return 0;
  18. }
  19. taos = taos_connect(argv[1], "root", "taosdata", NULL, 0);
  20. if (taos == NULL) {
  21. printf("failed to connect to db, reason:%s\n", taos_errstr(taos));
  22. exit(1);
  23. }
  24. result = taos_query(taos, "drop database demo");
  25. taos_free_result(result);
  26. result = taos_query(taos, "create database demo");
  27. code = taos_errno(result);
  28. if (code != 0) {
  29. printf("failed to create database, reason:%s\n", taos_errstr(result));
  30. taos_free_result(result);
  31. exit(1);
  32. }
  33. taos_free_result(result);
  34. result = taos_query(taos, "use demo");
  35. taos_free_result(result);
  36. // create table
  37. const char* sql = "create table m1 (ts timestamp, b bool, v1 tinyint, v2 smallint, v4 int, v8 bigint, f4 float, f8 double, bin binary(40), blob nchar(10))";
  38. result = taos_query(taos, sql);
  39. code = taos_errno(result);
  40. if (code != 0) {
  41. printf("failed to create table, reason:%s\n", taos_errstr(result));
  42. taos_free_result(result);
  43. exit(1);
  44. }
  45. taos_free_result(result);
  46. // sleep for one second to make sure table is created on data node
  47. // taosMsleep(1000);
  48. // insert 10 records
  49. struct {
  50. int64_t ts;
  51. int8_t b;
  52. int8_t v1;
  53. int16_t v2;
  54. int32_t v4;
  55. int64_t v8;
  56. float f4;
  57. double f8;
  58. char bin[40];
  59. char blob[80];
  60. } v = {0};
  61. int32_t boolLen = sizeof(int8_t);
  62. int32_t sintLen = sizeof(int16_t);
  63. int32_t intLen = sizeof(int32_t);
  64. int32_t bintLen = sizeof(int64_t);
  65. int32_t floatLen = sizeof(float);
  66. int32_t doubleLen = sizeof(double);
  67. int32_t binLen = sizeof(v.bin);
  68. int32_t ncharLen = 30;
  69. stmt = taos_stmt_init(taos);
  70. TAOS_MULTI_BIND params[10];
  71. params[0].buffer_type = TSDB_DATA_TYPE_TIMESTAMP;
  72. params[0].buffer_length = sizeof(v.ts);
  73. params[0].buffer = &v.ts;
  74. params[0].length = &bintLen;
  75. params[0].is_null = NULL;
  76. params[0].num = 1;
  77. params[1].buffer_type = TSDB_DATA_TYPE_BOOL;
  78. params[1].buffer_length = sizeof(v.b);
  79. params[1].buffer = &v.b;
  80. params[1].length = &boolLen;
  81. params[1].is_null = NULL;
  82. params[1].num = 1;
  83. params[2].buffer_type = TSDB_DATA_TYPE_TINYINT;
  84. params[2].buffer_length = sizeof(v.v1);
  85. params[2].buffer = &v.v1;
  86. params[2].length = &boolLen;
  87. params[2].is_null = NULL;
  88. params[2].num = 1;
  89. params[3].buffer_type = TSDB_DATA_TYPE_SMALLINT;
  90. params[3].buffer_length = sizeof(v.v2);
  91. params[3].buffer = &v.v2;
  92. params[3].length = &sintLen;
  93. params[3].is_null = NULL;
  94. params[3].num = 1;
  95. params[4].buffer_type = TSDB_DATA_TYPE_INT;
  96. params[4].buffer_length = sizeof(v.v4);
  97. params[4].buffer = &v.v4;
  98. params[4].length = &intLen;
  99. params[4].is_null = NULL;
  100. params[4].num = 1;
  101. params[5].buffer_type = TSDB_DATA_TYPE_BIGINT;
  102. params[5].buffer_length = sizeof(v.v8);
  103. params[5].buffer = &v.v8;
  104. params[5].length = &bintLen;
  105. params[5].is_null = NULL;
  106. params[5].num = 1;
  107. params[6].buffer_type = TSDB_DATA_TYPE_FLOAT;
  108. params[6].buffer_length = sizeof(v.f4);
  109. params[6].buffer = &v.f4;
  110. params[6].length = &floatLen;
  111. params[6].is_null = NULL;
  112. params[6].num = 1;
  113. params[7].buffer_type = TSDB_DATA_TYPE_DOUBLE;
  114. params[7].buffer_length = sizeof(v.f8);
  115. params[7].buffer = &v.f8;
  116. params[7].length = &doubleLen;
  117. params[7].is_null = NULL;
  118. params[7].num = 1;
  119. params[8].buffer_type = TSDB_DATA_TYPE_BINARY;
  120. params[8].buffer_length = sizeof(v.bin);
  121. params[8].buffer = v.bin;
  122. params[8].length = &binLen;
  123. params[8].is_null = NULL;
  124. params[8].num = 1;
  125. strcpy(v.blob, "一二三四五六七八九十");
  126. params[9].buffer_type = TSDB_DATA_TYPE_NCHAR;
  127. params[9].buffer_length = sizeof(v.blob);
  128. params[9].buffer = v.blob;
  129. params[9].length = &ncharLen;
  130. params[9].is_null = NULL;
  131. params[9].num = 1;
  132. char is_null = 1;
  133. sql = "insert into m1 values(?,?,?,?,?,?,?,?,?,?)";
  134. code = taos_stmt_prepare(stmt, sql, 0);
  135. if (code != 0){
  136. printf("failed to execute taos_stmt_prepare. code:0x%x\n", code);
  137. }
  138. v.ts = 1591060628000;
  139. for (int i = 0; i < 10; ++i) {
  140. v.ts += 1;
  141. for (int j = 1; j < 10; ++j) {
  142. params[j].is_null = ((i == j) ? &is_null : 0);
  143. }
  144. v.b = (int8_t)i % 2;
  145. v.v1 = (int8_t)i;
  146. v.v2 = (int16_t)(i * 2);
  147. v.v4 = (int32_t)(i * 4);
  148. v.v8 = (int64_t)(i * 8);
  149. v.f4 = (float)(i * 40);
  150. v.f8 = (double)(i * 80);
  151. for (int j = 0; j < sizeof(v.bin); ++j) {
  152. v.bin[j] = (char)(i + '0');
  153. }
  154. taos_stmt_bind_param(stmt, params);
  155. taos_stmt_add_batch(stmt);
  156. }
  157. if (taos_stmt_execute(stmt) != 0) {
  158. printf("failed to execute insert statement.\n");
  159. exit(1);
  160. }
  161. taos_stmt_close(stmt);
  162. // query the records
  163. stmt = taos_stmt_init(taos);
  164. taos_stmt_prepare(stmt, "SELECT * FROM m1 WHERE v1 > ? AND v2 < ?", 0);
  165. v.v1 = 5;
  166. v.v2 = 15;
  167. taos_stmt_bind_param(stmt, params + 2);
  168. if (taos_stmt_execute(stmt) != 0) {
  169. printf("failed to execute select statement.\n");
  170. exit(1);
  171. }
  172. result = taos_stmt_use_result(stmt);
  173. TAOS_ROW row;
  174. int rows = 0;
  175. int num_fields = taos_num_fields(result);
  176. TAOS_FIELD *fields = taos_fetch_fields(result);
  177. // fetch the records row by row
  178. while ((row = taos_fetch_row(result))) {
  179. char temp[256] = {0};
  180. rows++;
  181. taos_print_row(temp, row, fields, num_fields);
  182. printf("%s\n", temp);
  183. }
  184. if (rows == 2) {
  185. printf("two rows are fetched as expectation\n");
  186. } else {
  187. printf("expect two rows, but %d rows are fetched\n", rows);
  188. }
  189. taos_free_result(result);
  190. taos_stmt_close(stmt);
  191. return 0;
  192. }

view source code

Pattern-free writing example

Mode free write

  1. #include "taos.h"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <sys/time.h>
  5. #include <time.h>
  6. #include <unistd.h>
  7. #include <inttypes.h>
  8. #include <string.h>
  9. int numSuperTables = 8;
  10. int numChildTables = 4;
  11. int numRowsPerChildTable = 2048;
  12. static int64_t getTimeInUs() {
  13. struct timeval systemTime;
  14. gettimeofday(&systemTime, NULL);
  15. return (int64_t)systemTime.tv_sec * 1000000L + (int64_t)systemTime.tv_usec;
  16. }
  17. int main(int argc, char* argv[]) {
  18. TAOS_RES *result;
  19. const char* host = "127.0.0.1";
  20. const char* user = "root";
  21. const char* passwd = "taosdata";
  22. taos_options(TSDB_OPTION_TIMEZONE, "GMT-8");
  23. TAOS* taos = taos_connect(host, user, passwd, "", 0);
  24. if (taos == NULL) {
  25. printf("\033[31mfailed to connect to db, reason:%s\033[0m\n", taos_errstr(taos));
  26. exit(1);
  27. }
  28. const char* info = taos_get_server_info(taos);
  29. printf("server info: %s\n", info);
  30. info = taos_get_client_info(taos);
  31. printf("client info: %s\n", info);
  32. result = taos_query(taos, "drop database if exists db;");
  33. taos_free_result(result);
  34. usleep(100000);
  35. result = taos_query(taos, "create database db precision 'ms';");
  36. taos_free_result(result);
  37. usleep(100000);
  38. (void)taos_select_db(taos, "db");
  39. time_t ct = time(0);
  40. int64_t ts = ct * 1000;
  41. char* lineFormat = "sta%d,t0=true,t1=127i8,t2=32767i16,t3=%di32,t4=9223372036854775807i64,t9=11.12345f32,t10=22.123456789f64,t11=\"binaryTagValue\",t12=L\"ncharTagValue\" c0=true,c1=127i8,c2=32767i16,c3=2147483647i32,c4=9223372036854775807i64,c5=254u8,c6=32770u16,c7=2147483699u32,c8=9223372036854775899u64,c9=11.12345f32,c10=22.123456789f64,c11=\"binaryValue\",c12=L\"ncharValue\" %" PRId64;
  42. int lineNum = numSuperTables * numChildTables * numRowsPerChildTable;
  43. char** lines = calloc((size_t)lineNum, sizeof(char*));
  44. int l = 0;
  45. for (int i = 0; i < numSuperTables; ++i) {
  46. for (int j = 0; j < numChildTables; ++j) {
  47. for (int k = 0; k < numRowsPerChildTable; ++k) {
  48. char* line = calloc(512, 1);
  49. snprintf(line, 512, lineFormat, i, j, ts + 10 * l);
  50. lines[l] = line;
  51. ++l;
  52. }
  53. }
  54. }
  55. printf("%s\n", "begin taos_insert_lines");
  56. int64_t begin = getTimeInUs();
  57. TAOS_RES *res = taos_schemaless_insert(taos, lines, lineNum, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_MILLI_SECONDS);
  58. int64_t end = getTimeInUs();
  59. printf("code: %s. time used: %" PRId64 "\n", taos_errstr(res), end-begin);
  60. taos_free_result(res);
  61. return 0;
  62. }

view source code

Subscription and consumption example

Subscribe and consume

C/C++ - 图2info

More example code and downloads are available at GitHub. You can find it in the installation directory under the examples/c path. This directory has a makefile and can be compiled under Linux/macOS by executing make directly. Hint: When compiling in an ARM environment, please remove -msse4.2 from the makefile. This option is only supported on the x64/x86 hardware platforms.

API Reference

The following describes the basic API, synchronous API, asynchronous API, subscription API, and schemaless write API of TDengine client driver, respectively.

Basic API

The base API is used to do things like create database connections and provide a runtime environment for the execution of other APIs.

  • void taos_init()

    Initializes the runtime environment. If the API is not actively called, the driver will automatically call the API when taos_connect() is called, so the program generally does not need to call it manually.

  • void taos_cleanup()

    Cleans up the runtime environment and should be called before the application exits.

  • int taos_options(TSDB_OPTION option, const void * arg, ...)

    Set client options, currently supports region setting (TSDB_OPTION_LOCALE), character set (TSDB_OPTION_CHARSET), time zone (TSDB_OPTION_TIMEZONE), configuration file path (TSDB_OPTION_CONFIGDIR). The region setting, character set, and time zone default to the current settings of the operating system.

  • char *taos_get_client_info()

    Get client version information.

  • TAOS *taos_connect(const char *host, const char *user, const char *pass, const char *db, int port)

    Creates a database connection and initializes the connection context. Among the parameters required from the user are:

    • host: FQDN of any node in the TDengine cluster
    • user: user name
    • pass: password
    • db: the database name. Even if the user does not provide this, the connection will still work correctly. The user can create a new database through this connection. If the user provides the database name, it means that the database has already been created and the connection can be used for regular operations on the database.
    • port: the port the taosd program is listening on

    NULL indicates a failure. The application needs to save the returned parameters for subsequent use.

    C/C++ - 图3info

    The same process can connect to multiple TDengine clusters according to different host/port

  • char *taos_get_server_info(TAOS *taos)

    Get server-side version information.

  • int taos_select_db(TAOS *taos, const char *db)

    Set the current default database to db.

  • void taos_close(TAOS *taos)

    Closes the connection, where taos is the handle returned by taos_connect().

Synchronous query APIs

The APIs described in this subsection are all synchronous interfaces. After being called by the application, it blocks and waits for a response until it gets a return result or an error message.

  • TAOS_RES* taos_query(TAOS *taos, const char *sql)

    Executes an SQL command, either a DQL, DML, or DDL statement. The taos parameter is a handle obtained with taos_connect(). If the return value is NULL this does not necessarily indicate a failure. You can get the error code, if any, by parsing the error code in the result set with the taos_errno() function.

  • int taos_result_precision(TAOS_RES *res)

    Returns the precision of the result set timestamp field, 0 for milliseconds, 1 for microseconds, and 2 for nanoseconds.

  • TAOS_ROW taos_fetch_row(TAOS_RES *res)

    Fetch the data in the query result set by row.

  • int taos_fetch_block(TAOS_RES *res, TAOS_ROW *rows)

    Batch fetches the data in the query result set. The return value is the number of rows of the fetched data.

  • int taos_num_fields(TAOS_RES *res) and int taos_field_count(TAOS_RES *res)

    These two APIs are equivalent and are used to get the number of columns in the query result set.

  • int* taos_fetch_lengths(TAOS_RES *res)

    Gets the lengths of each field in the result set. The return value is an array whose length is the number of columns in the result set.

  • int taos_affected_rows(TAOS_RES *res)

    Get the number of rows affected by the executed SQL statement.

  • TAOS_FIELD *taos_fetch_fields(TAOS_RES *res)

    Gets the properties of each column of the query result set (column name, column data type, column length), used in conjunction with taos_num_fields() to parse a tuple (one row) of data returned by taos_fetch_row(). The structure of TAOS_FIELD is as follows.

  1. typedef struct taosField {
  2. char name[65]; // column name
  3. uint8_t type; // data type
  4. int16_t bytes; // length, in bytes
  5. } TAOS_FIELD;
  • void taos_stop_query(TAOS_RES *res)

    Stops the execution of the current query.

  • void taos_free_result(TAOS_RES *res)

    Frees the query result set and the associated resources. Be sure to call this API to free the resources after the query is completed. Failing to call this, may lead to a memory leak in the application. However, note that the application will crash if you call a function like taos_consume() to get the query results after freeing the resources.

  • char *taos_errstr(TAOS_RES *res)

    Get the reason for the failure of the last API call. The return value is an error message identified by a string.

  • int taos_errno(TAOS_RES *res)

    Get the reason for the last API call failure. The return value is the error code.

C/C++ - 图4note

TDengine version 2.0 and above recommends that each thread of a database application create a separate connection or a connection pool based on threads. It is not recommended to pass the connection (TAOS*) structure to different threads for shared use in the application. Queries, writes, and other operations issued that are based on TAOS structures are multi-thread safe, but state quantities such as the “USE statement” may interfere between threads. In addition, the C connector can dynamically create new database-oriented connections on demand (this procedure is not visible to the user), and it is recommended that taos_close() be called only at the final exit of the program to close the connection.

Asynchronous query API

TDengine also provides a set of asynchronous API to handle data insertion and query operations with a higher performance. Given the same hardware and software environment, the asynchronous API can run data insertion 2 to 4 times faster than the synchronous API. The asynchronous API is called non-blocking and returns immediately before the system completes a specific database operation. The calling thread can go to work on other tasks, which can improve the performance of the whole application. Asynchronous APIs are particularly advantageous in the case of severe network latency.

The asynchronous APIs require the application to provide a callback function with the following parameters: the first two parameters are consistent, and the third parameter depends on the API. The first parameter, param, is provided to the system when the application calls the asynchronous API. It is used for the callback so that the application can retrieve the context of the specific operation, depending on the implementation. The second parameter is the result set of the SQL operation. If it is NULL, such as insert operation, it means that there are no records returned, and if it is not NULL, such as select operation, it means that there are records returned.

The asynchronous API has relatively high user requirements, so users can use it selectively according to specific application scenarios. The following are two important asynchronous APIs.

  • void taos_query_a(TAOS *taos, const char *sql, void (*fp)(void *param, TAOS_RES *, int code), void *param);

    Execute SQL command asynchronously.

    • taos: the database connection returned by calling taos_connect()
    • sql: the SQL statement to be executed
    • fp: user-defined callback function whose third parameter code is used to indicate whether the operation was successful or not, 0 means success, a negative number means failure (call taos_errstr() to get the reason for failure). When defining the callback function, the application mainly handles the second parameter TAOS_RES *, which is the result set returned by the query
    • param: the application provides a parameter for the callback
  • void taos_fetch_rows_a(TAOS_RES *res, void (*fp)(void *param, TAOS_RES *, int numOfRows), void *param);

    Batch get the result set of an asynchronous query, which can only be used with taos_query_a(). The parameters are:

    • res: the result set returned by the taos_query_a() callback
    • fp: callback function. Its parameter param is a user-definable parameter structure passed to the callback function; numOfRows is the number of rows of the fetched data (not a function of the entire query result set). In the callback function, the application can iterate forward to fetch each row of records in the batch by calling taos_fetch_row(). After reading all the rows in a block, the application needs to continue calling taos_fetch_rows_a() in the callback function to get the next batch of rows for processing until the number of rows returned, numOfRows, is zero (result return complete) or the number of rows is negative (query error).

All TDengine’s asynchronous APIs use a non-blocking call pattern. Applications can open multiple tables simultaneously using multiple threads and perform queries or inserts on each open table at the same time. It is important to note that client applications must ensure that operations on the same table are fully serialized. i.e., no second insert or query operation can be performed while an insert or query operation on the same table is incomplete (not returned).

Parameter Binding API

In addition to direct calls to taos_query() to perform queries, TDengine also provides a set of bind APIs that supports parameter binding, similar in style to MySQL. TDengine currently only supports using a question mark ? to represent the parameter to be bound.

Starting with versions 2.1.1.0 and 2.1.2.0, TDengine has significantly improved the bind APIs to support data writing (INSERT) scenarios. This avoids the resource consumption of SQL syntax parsing when writing data through the parameter binding interface, thus significantly improving write performance in most cases. A typical operation, in this case, is as follows.

  1. call taos_stmt_init() to create the parameter binding object.
  2. call taos_stmt_prepare() to parse the INSERT statement.
  3. call taos_stmt_set_tbname() to set the table name if it is reserved in the INSERT statement but not the TAGS.
  4. call taos_stmt_set_tbname_tags() to set the table name and TAGS values if the table name and TAGS are reserved in the INSERT statement (for example, if the INSERT statement takes an automatic table build).
  5. call taos_stmt_bind_param_batch() to set the value of VALUES in multiple columns, or call taos_stmt_bind_param() to set the value of VALUES in a single row.
  6. call taos_stmt_add_batch() to add the currently bound parameters to the batch.
  7. you can repeat steps 3 to 6 to add more rows of data to the batch.
  8. call taos_stmt_execute() to execute the prepared batch instructions.
  9. When execution is complete, call taos_stmt_close() to release all resources.

Note: If taos_stmt_execute() succeeds, you can reuse the parsed result of taos_stmt_prepare() to bind new data in steps 3 to 6 if you don’t need to change the SQL command. However, if there is an execution error, it is not recommended to continue working in the current context but release the resources and start again with taos_stmt_init() steps.

The specific functions related to the interface are as follows (see also the prepare.c file for the way to use the corresponding functions)

  • TAOS_STMT* taos_stmt_init(TAOS *taos)

    Creates a TAOS_STMT object for subsequent calls.

  • int taos_stmt_prepare(TAOS_STMT *stmt, const char *sql, unsigned long length)

    Parse a SQL command, and bind the parsed result and parameter information to stmt. If the parameter length is greater than 0, use this parameter as the length of the SQL command. If it is equal to 0, the length of the SQL command will be determined automatically.

  • int taos_stmt_bind_param(TAOS_STMT *stmt, TAOS_BIND *bind)

    Not as efficient as taos_stmt_bind_param_batch(), but can support non-INSERT type SQL statements. To bind parameters, bind points to an array (representing the row of data to be bound), making sure that the number and order of the elements in this array are the same as the parameters in the SQL statement. taos_bind is used similarly to MYSQL_BIND in MySQL, as defined below.

    1. typedef struct TAOS_BIND {
    2. int buffer_type;
    3. void * buffer;
    4. uintptr_t buffer_length; // not in use
    5. uintptr_t * length;
    6. int * is_null;
    7. int is_unsigned; // not in use
    8. int * error; // not in use
    9. } TAOS_BIND;
  • int taos_stmt_set_tbname(TAOS_STMT* stmt, const char* name)

    (Available in 2.1.1.0 and later versions, only supported for replacing parameter values in INSERT statements) When the table name in the SQL command uses ? placeholder, you can use this function to bind a specific table name.

  • int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags)

    (Available in 2.1.2.0 and later versions, only supported for replacing parameter values in INSERT statements) When the table name and TAGS in the SQL command both use ? , you can use this function to bind the specific table name and the specific TAGS value. The most typical usage scenario is an INSERT statement that uses the automatic table building function (the current version does not support specifying specific TAGS columns.) The number of columns in the TAGS parameter needs to be the same as the number of TAGS requested in the SQL command.

  • int taos_stmt_bind_param_batch(TAOS_STMT* stmt, TAOS_MULTI_BIND* bind)

    (Available in 2.1.1.0 and later versions, only supported for replacing parameter values in INSERT statements) To pass the data to be bound in a multi-column manner, it is necessary to ensure that the order of the data columns and the number of columns given here are the same as the VALUES parameter in the SQL statement. The specific definition of TAOS_MULTI_BIND is as follows.

    1. typedef struct TAOS_MULTI_BIND {
    2. int buffer_type;
    3. void * buffer;
    4. uintptr_t buffer_length;
    5. uintptr_t * length;
    6. char * is_null;
    7. int num; // the number of columns
    8. } TAOS_MULTI_BIND;
  • int taos_stmt_add_batch(TAOS_STMT *stmt)

    Adds the currently bound parameter to the batch. After calling this function, you can call taos_stmt_bind_param() or taos_stmt_bind_param_batch() again to bind a new parameter. Note that this function only supports INSERT/IMPORT statements. Other SQL command such as SELECT will return an error.

  • int taos_stmt_execute(TAOS_STMT *stmt)

    Execute the prepared statement. Currently, a statement can only be executed once.

  • TAOS_RES* taos_stmt_use_result(TAOS_STMT *stmt)

    Gets the result set of a statement. Use the result set in the same way as in the non-parametric call. When finished, taos_free_result() should be called on this result set to free resources.

  • int taos_stmt_close(TAOS_STMT *stmt)

    Finish execution and release all resources.

  • char * taos_stmt_errstr(TAOS_STMT *stmt)

    (Available in 2.1.3.0 and later versions) Used to get error information if other STMT APIs return errors (return error codes or null pointers).

Schemaless Writing API

In addition to writing data using the SQL method or the parameter binding API, writing can also be done using schemaless writing, which eliminates the need to create a super table/data sub-table structure in advance and writes the data directly. The TDengine system automatically creates and maintains the required table structure based on the written data content. The use of schemaless writing is described in the chapter Schemaless Writing, and the C/C++ API used with it is described here.

  • TAOS_RES* taos_schemaless_insert(TAOS* taos, const char* lines[], int numLines, int protocol, int precision)

    Function description This interface writes the text data of the line protocol to TDengine.

    Parameter description

    • taos: database connection, established by the taos_connect() function.
    • lines: text data. A pattern-free text string that meets the parsing format requirements.
    • numLines: the number of lines of text data, cannot be 0.
    • protocol: the protocol type of the lines, used to identify the text data format.
    • precision: precision string for the timestamp in the text data.

    return value TAOS_RES structure, application can get error message by using taos_errstr() and also error code by using taos_errno(). In some cases, the returned TAOS_RES is NULL, and it is still possible to call taos_errno() to safely get the error code information. The returned TAOS_RES needs to be freed by the caller in order to avoid memory leaks.

    Description The protocol type is enumerated and contains the following three formats.

    • TSDB_SML_LINE_PROTOCOL: InfluxDB line protocol (Line Protocol)
    • TSDB_SML_TELNET_PROTOCOL: OpenTSDB Telnet Text Line Protocol
    • TSDB_SML_JSON_PROTOCOL: OpenTSDB Json protocol format

    The timestamp resolution definitions are in the taos.h file, as follows

    • TSDB_SML_TIMESTAMP_NOT_CONFIGURED = 0,
    • TSDB_SML_TIMESTAMP_HOURS,
    • TSDB_SML_TIMESTAMP_MINUTES,
    • TSDB_SML_TIMESTAMP_SECONDS,
    • TSDB_SML_TIMESTAMP_MILLI_SECONDS,
    • TSDB_SML_TIMESTAMP_MICRO_SECONDS,
    • TSDB_SML_TIMESTAMP_NANO_SECONDS

    Note that the timestamp resolution parameter only takes effect when the protocol type is SML_LINE_PROTOCOL. For OpenTSDB’s text protocol, timestamp resolution follows its official resolution rules - time precision is confirmed by the number of characters contained in the timestamp.

    Supported Versions This feature interface is supported from version 2.3.0.0.