C/C++ Connector

C/C++ 开发人员可以使用 TDengine 的客户端驱动,即 C/C++连接器 (以下都用 TDengine 客户端驱动表示),开发自己的应用来连接 TDengine 集群完成数据存储、查询以及其他功能。TDengine 客户端驱动的 API 类似于 MySQL 的 C API。应用程序使用时,需要包含 TDengine 头文件 taos.h,里面列出了提供的 API 的函数原型;应用程序还要链接到所在平台上对应的动态库。

1. #include <taos.h>

TDengine 服务端或客户端安装后,taos.h 位于:

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

TDengine 客户端驱动的动态库位于:

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

支持的平台

请参考支持的平台列表

支持的版本

TDengine 客户端驱动的版本号与 TDengine 服务端的版本号是一一对应的强对应关系,建议使用与 TDengine 服务端完全相同的客户端驱动。虽然低版本的客户端驱动在前三段版本号一致(即仅第四段版本号不同)的情况下也能够与高版本的服务端相兼容,但这并非推荐用法。强烈不建议使用高版本的客户端驱动访问低版本的服务端。

安装步骤

TDengine 客户端驱动的安装请参考 安装指南

建立连接

使用客户端驱动访问 TDengine 集群的基本过程为:建立连接、查询和写入、关闭连接、清除资源。

下面为建立连接的示例代码,其中省略了查询和写入部分,展示了如何建立连接、关闭连接以及清除资源。

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. }

7. /* put your code here for read and write */

9. taos_close(taos);
10. taos_cleanup();

在上面的示例代码中, taos_connect() 建立到客户端程序所在主机的 6030 端口的连接,taos_close()关闭当前连接,taos_cleanup()清除客户端驱动所申请和使用的资源。

C/C++ - 图1note
  • 如未特别说明,当 API 的返回值是整数时,0 代表成功,其它是代表失败原因的错误码,当返回值是指针时, NULL 表示失败。
  • 所有的错误码以及对应的原因描述在 taoserror.h 文件中。

示例程序

本节展示了使用客户端驱动访问 TDengine 集群的常见访问方式的示例代码。

同步查询示例

同步查询

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. */

16. // TAOS standard API example. The same syntax as MySQL, but only a subset
17. // to compile: gcc -o demo demo.c -ltaos

19. #include <inttypes.h>
20. #include <stdio.h>
21. #include <stdlib.h>
22. #include <string.h>
23. #include "taos.h"  // TAOS header file

25. static void queryDB(TAOS *taos, char *command) {
26. int i;
27. TAOS_RES *pSql = NULL;
28. int32_t   code = -1;

30. for (i = 0; i < 5; i++) {
31. if (NULL != pSql) {
32. taos_free_result(pSql);
33. pSql = NULL;
34. }

36. pSql = taos_query(taos, command);
37. code = taos_errno(pSql);
38. if (0 == code) {
39. break;
40. }
41. }

43. if (code != 0) {
44. fprintf(stderr, "Failed to run %s, reason: %s\n", command, taos_errstr(pSql));
45. taos_free_result(pSql);
46. taos_close(taos);
47. exit(EXIT_FAILURE);
48. }

50. taos_free_result(pSql);
51. }

53. void Test(TAOS *taos, char *qstr, int i);

55. int main(int argc, char *argv[]) {
56. char      qstr[1024];

58. // connect to server
59. if (argc < 2) {
60. printf("please input server-ip \n");
61. return 0;
62. }

64. TAOS *taos = taos_connect(argv[1], "root", "taosdata", NULL, 0);
65. if (taos == NULL) {
66. printf("failed to connect to server, reason:%s\n", "null taos"/*taos_errstr(taos)*/);
67. exit(1);
68. }
69. for (int i = 0; i < 100; i++) {
70. Test(taos, qstr, i);
71. }
72. taos_close(taos);
73. taos_cleanup();
74. }
75. void Test(TAOS *taos, char *qstr, int index)  {
76. printf("==================test at %d\n================================", index);
77. queryDB(taos, "drop database if exists demo");
78. queryDB(taos, "create database demo");
79. TAOS_RES *result;
80. queryDB(taos, "use demo");

82. queryDB(taos, "create table m1 (ts timestamp, ti tinyint, si smallint, i int, bi bigint, f float, d double, b binary(10))");
83. printf("success to create table\n");

85. int i = 0;
86. for (i = 0; i < 10; ++i) {
87. 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");
88. printf("qstr: %s\n", qstr);

90. // note: how do you wanna do if taos_query returns non-NULL
91. // if (taos_query(taos, qstr)) {
92. //   printf("insert row: %i, reason:%s\n", i, taos_errstr(taos));
93. // }
94. TAOS_RES *result1 = taos_query(taos, qstr);
95. if (result1 == NULL || taos_errno(result1) != 0) {
96. printf("failed to insert row, reason:%s\n", taos_errstr(result1));
97. taos_free_result(result1);
98. exit(1);
99. } else {
100. printf("insert row: %i\n", i);
101. }
102. taos_free_result(result1);
103. }
104. printf("success to insert rows, total %d rows\n", i);

106. // query the records
107. sprintf(qstr, "SELECT * FROM m1");
108. result = taos_query(taos, qstr);
109. if (result == NULL || taos_errno(result) != 0) {
110. printf("failed to select, reason:%s\n", taos_errstr(result));
111. taos_free_result(result);
112. exit(1);
113. }

115. TAOS_ROW    row;
116. int         rows = 0;
117. int         num_fields = taos_field_count(result);
118. TAOS_FIELD *fields = taos_fetch_fields(result);

120. printf("num_fields = %d\n", num_fields);
121. printf("select * from table, result:\n");
122. // fetch the records row by row
123. while ((row = taos_fetch_row(result))) {
124. char temp[1024] = {0};
125. rows++;
126. taos_print_row(temp, row, fields, num_fields);
127. printf("%s\n", temp);
128. }

130. taos_free_result(result);
131. printf("====demo end====\n\n");
132. }

查看源码 格式化输出不同类型字段函数 taos_print_row

1. int taos_print_row(char *str, TAOS_ROW row, TAOS_FIELD *fields, int num_fields) {
2. int32_t len = 0;
3. for (int i = 0; i < num_fields; ++i) {
4. if (i > 0) {
5. str[len++] = ' ';
6. }

8. if (row[i] == NULL) {
9. len += sprintf(str + len, "%s", TSDB_DATA_NULL_STR);
10. continue;
11. }

13. switch (fields[i].type) {
14. case TSDB_DATA_TYPE_TINYINT:
15. len += sprintf(str + len, "%d", *((int8_t *)row[i]));
16. break;

18. case TSDB_DATA_TYPE_UTINYINT:
19. len += sprintf(str + len, "%u", *((uint8_t *)row[i]));
20. break;

22. case TSDB_DATA_TYPE_SMALLINT:
23. len += sprintf(str + len, "%d", *((int16_t *)row[i]));
24. break;

26. case TSDB_DATA_TYPE_USMALLINT:
27. len += sprintf(str + len, "%u", *((uint16_t *)row[i]));
28. break;

30. case TSDB_DATA_TYPE_INT:
31. len += sprintf(str + len, "%d", *((int32_t *)row[i]));
32. break;

34. case TSDB_DATA_TYPE_UINT:
35. len += sprintf(str + len, "%u", *((uint32_t *)row[i]));
36. break;

38. case TSDB_DATA_TYPE_BIGINT:
39. len += sprintf(str + len, "%" PRId64, *((int64_t *)row[i]));
40. break;

42. case TSDB_DATA_TYPE_UBIGINT:
43. len += sprintf(str + len, "%" PRIu64, *((uint64_t *)row[i]));
44. break;

46. case TSDB_DATA_TYPE_FLOAT: {
47. float fv = 0;
48. fv = GET_FLOAT_VAL(row[i]);
49. len += sprintf(str + len, "%f", fv);
50. } break;

52. case TSDB_DATA_TYPE_DOUBLE: {
53. double dv = 0;
54. dv = GET_DOUBLE_VAL(row[i]);
55. len += sprintf(str + len, "%lf", dv);
56. } break;

58. case TSDB_DATA_TYPE_BINARY:
59. case TSDB_DATA_TYPE_NCHAR: {
60. int32_t charLen = varDataLen((char *)row[i] - VARSTR_HEADER_SIZE);
61. if (fields[i].type == TSDB_DATA_TYPE_BINARY) {
62. assert(charLen <= fields[i].bytes && charLen >= 0);
63. } else {
64. assert(charLen <= fields[i].bytes * TSDB_NCHAR_SIZE && charLen >= 0);
65. }

67. memcpy(str + len, row[i], charLen);
68. len += charLen;
69. } break;

71. case TSDB_DATA_TYPE_TIMESTAMP:
72. len += sprintf(str + len, "%" PRId64, *((int64_t *)row[i]));
73. break;

75. case TSDB_DATA_TYPE_BOOL:
76. len += sprintf(str + len, "%d", *((int8_t *)row[i]));
77. default:
78. break;
79. }
80. }
81. str[len] = 0;

83. return len;
84. }

异步查询示例

异步查询

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. */

16. // TAOS asynchronous API example
17. // this example opens multiple tables, insert/retrieve multiple tables
18. // it is used by TAOS internally for one performance testing
19. // to compiple: gcc -o asyncdemo asyncdemo.c -ltaos

21. #include <stdio.h>
22. #include <stdlib.h>
23. #include <sys/time.h>
24. #include <unistd.h>
25. #include <string.h>
26. #include <inttypes.h>
27. #include "taos.h"

29. int     points = 5;
30. int     numOfTables = 3;
31. int     tablesInsertProcessed = 0;
32. int     tablesSelectProcessed = 0;
33. int64_t st, et;

35. typedef struct {
36. int       id;
37. TAOS     *taos;
38. char      name[32];
39. time_t    timeStamp;
40. int       value;
41. int       rowsInserted;
42. int       rowsTried;
43. int       rowsRetrieved;
44. } STable;

46. void taos_insert_call_back(void *param, TAOS_RES *tres, int code);
47. void taos_select_call_back(void *param, TAOS_RES *tres, int code);
48. void shellPrintError(TAOS *taos);

50. static void queryDB(TAOS *taos, char *command) {
51. int i;
52. TAOS_RES *pSql = NULL;
53. int32_t   code = -1;

55. for (i = 0; i < 5; i++) {
56. if (NULL != pSql) {
57. taos_free_result(pSql);
58. pSql = NULL;
59. }

61. pSql = taos_query(taos, command);
62. code = taos_errno(pSql);
63. if (0 == code) {
64. break;
65. }
66. }

68. if (code != 0) {
69. fprintf(stderr, "Failed to run %s, reason: %s\n", command, taos_errstr(pSql));
70. taos_free_result(pSql);
71. taos_close(taos);
72. taos_cleanup();
73. exit(EXIT_FAILURE);
74. }

76. taos_free_result(pSql);
77. }

79. int main(int argc, char *argv[])
80. {
81. TAOS   *taos;
82. struct  timeval systemTime;
83. int     i;
84. char    sql[1024]  = { 0 };
85. char    prefix[20] = { 0 };
86. char    db[128]    = { 0 };
87. STable *tableList;

89. if (argc != 5) {
90. printf("usage: %s server-ip dbname rowsPerTable numOfTables\n", argv[0]);
91. exit(0);
92. }

94. // a simple way to parse input parameters
95. if (argc >= 3) strncpy(db, argv[2], sizeof(db) - 1);
96. if (argc >= 4) points = atoi(argv[3]);
97. if (argc >= 5) numOfTables = atoi(argv[4]);

99. size_t size = sizeof(STable) * (size_t)numOfTables;
100. tableList = (STable *)malloc(size);
101. memset(tableList, 0, size);

103. taos = taos_connect(argv[1], "root", "taosdata", NULL, 0);
104. if (taos == NULL)
105. shellPrintError(taos);

107. printf("success to connect to server\n");

109. sprintf(sql, "drop database if exists %s", db);
110. queryDB(taos, sql);

112. sprintf(sql, "create database %s", db);
113. queryDB(taos, sql);

115. sprintf(sql, "use %s", db);
116. queryDB(taos, sql);

118. strcpy(prefix, "asytbl_");
119. for (i = 0; i < numOfTables; ++i) {
120. tableList[i].id = i;
121. tableList[i].taos = taos;
122. sprintf(tableList[i].name, "%s%d", prefix, i);
123. sprintf(sql, "create table %s%d (ts timestamp, volume bigint)", prefix, i);
124. queryDB(taos, sql);
125. }

127. gettimeofday(&systemTime, NULL);
128. for (i = 0; i < numOfTables; ++i)
129. tableList[i].timeStamp = (time_t)(systemTime.tv_sec) * 1000 + systemTime.tv_usec / 1000;

131. printf("success to create tables, press any key to insert\n");
132. getchar();

134. printf("start to insert...\n");
135. gettimeofday(&systemTime, NULL);
136. st = systemTime.tv_sec * 1000000 + systemTime.tv_usec;

138. tablesInsertProcessed = 0;
139. tablesSelectProcessed = 0;

141. for (i = 0; i<numOfTables; ++i) {
142. // insert records in asynchronous API
143. sprintf(sql, "insert into %s values(%ld, 0)", tableList[i].name, 1546300800000 + i);
144. taos_query_a(taos, sql, taos_insert_call_back, (void *)(tableList + i));
145. }

147. printf("once insert finished, presse any key to query\n");
148. getchar();

150. while(1) {
151. if (tablesInsertProcessed < numOfTables) {
152. printf("wait for process finished\n");
153. sleep(1);
154. continue;
155. }

157. break;
158. }

160. printf("start to query...\n");
161. gettimeofday(&systemTime, NULL);
162. st = systemTime.tv_sec * 1000000 + systemTime.tv_usec;

165. for (i = 0; i < numOfTables; ++i) {
166. // select records in asynchronous API
167. sprintf(sql, "select * from %s", tableList[i].name);
168. taos_query_a(taos, sql, taos_select_call_back, (void *)(tableList + i));
169. }

171. printf("\nonce finished, press any key to exit\n");
172. getchar();

174. while(1) {
175. if (tablesSelectProcessed < numOfTables) {
176. printf("wait for process finished\n");
177. sleep(1);
178. continue;
179. }

181. break;
182. }

184. for (i = 0; i<numOfTables; ++i)  {
185. printf("%s inserted:%d retrieved:%d\n", tableList[i].name, tableList[i].rowsInserted, tableList[i].rowsRetrieved);
186. }

188. taos_close(taos);
189. free(tableList);

191. printf("==== async demo end====\n");
192. printf("\n");
193. return 0;
194. }

196. void shellPrintError(TAOS *con)
197. {
198. fprintf(stderr, "TDengine error: %s\n", taos_errstr(con));
199. taos_close(con);
200. taos_cleanup();
201. exit(1);
202. }

204. void taos_insert_call_back(void *param, TAOS_RES *tres, int code)
205. {
206. STable *pTable = (STable *)param;
207. struct  timeval systemTime;
208. char    sql[128];

210. pTable->rowsTried++;

212. if (code < 0)  {
213. printf("%s insert failed, code:%d, rows:%d\n", pTable->name, code, pTable->rowsTried);
214. }
215. else if (code == 0) {
216. printf("%s not inserted\n", pTable->name);
217. }
218. else {
219. pTable->rowsInserted++;
220. }

222. if (pTable->rowsTried < points) {
223. // for this demo, insert another record
224. sprintf(sql, "insert into %s values(%ld, %d)", pTable->name, 1546300800000+pTable->rowsTried*1000, pTable->rowsTried);
225. taos_query_a(pTable->taos, sql, taos_insert_call_back, (void *)pTable);
226. }
227. else {
228. printf("%d rows data are inserted into %s\n", points, pTable->name);
229. tablesInsertProcessed++;
230. if (tablesInsertProcessed >= numOfTables) {
231. gettimeofday(&systemTime, NULL);
232. et = systemTime.tv_sec * 1000000 + systemTime.tv_usec;
233. printf("%" PRId64 " mseconds to insert %d data points\n", (et - st) / 1000, points*numOfTables);
234. }
235. }

237. taos_free_result(tres);
238. }

240. void taos_retrieve_call_back(void *param, TAOS_RES *tres, int numOfRows)
241. {
242. STable   *pTable = (STable *)param;
243. struct timeval systemTime;

245. if (numOfRows > 0) {

247. for (int i = 0; i<numOfRows; ++i) {
248. // synchronous API to retrieve a row from batch of records
249. /*TAOS_ROW row = */(void)taos_fetch_row(tres);
250. // process row
251. }

253. pTable->rowsRetrieved += numOfRows;

255. // retrieve next batch of rows
256. taos_fetch_rows_a(tres, taos_retrieve_call_back, pTable);

258. }
259. else {
260. if (numOfRows < 0)
261. printf("%s retrieve failed, code:%d\n", pTable->name, numOfRows);

263. //taos_free_result(tres);
264. printf("%d rows data retrieved from %s\n", pTable->rowsRetrieved, pTable->name);

266. tablesSelectProcessed++;
267. if (tablesSelectProcessed >= numOfTables) {
268. gettimeofday(&systemTime, NULL);
269. et = systemTime.tv_sec * 1000000 + systemTime.tv_usec;
270. printf("%" PRId64 " mseconds to query %d data rows\n", (et - st) / 1000, points * numOfTables);
271. }

273. taos_free_result(tres);
274. }

277. }

279. void taos_select_call_back(void *param, TAOS_RES *tres, int code)
280. {
281. STable *pTable = (STable *)param;

283. if (code == 0 && tres) {
284. // asynchronous API to fetch a batch of records
285. taos_fetch_rows_a(tres, taos_retrieve_call_back, pTable);
286. }
287. else {
288. printf("%s select failed, code:%d\n", pTable->name, code);
289. taos_free_result(tres);
290. taos_cleanup();
291. exit(1);
292. }
293. }

查看源码

参数绑定示例

参数绑定

1. // TAOS standard API example. The same syntax as MySQL, but only a subet
2. // to compile: gcc -o prepare prepare.c -ltaos

4. #include <stdio.h>
5. #include <stdlib.h>
6. #include <string.h>
7. #include "taos.h"

9. void taosMsleep(int mseconds);

11. int main(int argc, char *argv[])
12. {
13. TAOS     *taos;
14. TAOS_RES *result;
15. int      code;
16. TAOS_STMT *stmt;

18. // connect to server
19. if (argc < 2) {
20. printf("please input server ip \n");
21. return 0;
22. }

24. taos = taos_connect(argv[1], "root", "taosdata", NULL, 0);
25. if (taos == NULL) {
26. printf("failed to connect to db, reason:%s\n", taos_errstr(taos));
27. exit(1);
28. }

30. result = taos_query(taos, "drop database demo");
31. taos_free_result(result);

33. result = taos_query(taos, "create database demo");
34. code = taos_errno(result);
35. if (code != 0) {
36. printf("failed to create database, reason:%s\n", taos_errstr(result));
37. taos_free_result(result);
38. exit(1);
39. }
40. taos_free_result(result);

42. result = taos_query(taos, "use demo");
43. taos_free_result(result);

45. // create table
46. 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))";
47. result = taos_query(taos, sql);
48. code = taos_errno(result);
49. if (code != 0) {
50. printf("failed to create table, reason:%s\n", taos_errstr(result));
51. taos_free_result(result);
52. exit(1);
53. }
54. taos_free_result(result);

56. // sleep for one second to make sure table is created on data node
57. // taosMsleep(1000);

59. // insert 10 records
60. struct {
61. int64_t ts;
62. int8_t b;
63. int8_t v1;
64. int16_t v2;
65. int32_t v4;
66. int64_t v8;
67. float f4;
68. double f8;
69. char bin[40];
70. char blob[80];
71. } v = {0};

73. int32_t boolLen = sizeof(int8_t);
74. int32_t sintLen = sizeof(int16_t);
75. int32_t intLen = sizeof(int32_t);
76. int32_t bintLen = sizeof(int64_t);
77. int32_t floatLen = sizeof(float);
78. int32_t doubleLen = sizeof(double);
79. int32_t binLen = sizeof(v.bin);
80. int32_t ncharLen = 30;

82. stmt = taos_stmt_init(taos);
83. TAOS_MULTI_BIND params[10];
84. params[0].buffer_type = TSDB_DATA_TYPE_TIMESTAMP;
85. params[0].buffer_length = sizeof(v.ts);
86. params[0].buffer = &v.ts;
87. params[0].length = &bintLen;
88. params[0].is_null = NULL;
89. params[0].num = 1;

91. params[1].buffer_type = TSDB_DATA_TYPE_BOOL;
92. params[1].buffer_length = sizeof(v.b);
93. params[1].buffer = &v.b;
94. params[1].length = &boolLen;
95. params[1].is_null = NULL;
96. params[1].num = 1;

98. params[2].buffer_type = TSDB_DATA_TYPE_TINYINT;
99. params[2].buffer_length = sizeof(v.v1);
100. params[2].buffer = &v.v1;
101. params[2].length = &boolLen;
102. params[2].is_null = NULL;
103. params[2].num = 1;

105. params[3].buffer_type = TSDB_DATA_TYPE_SMALLINT;
106. params[3].buffer_length = sizeof(v.v2);
107. params[3].buffer = &v.v2;
108. params[3].length = &sintLen;
109. params[3].is_null = NULL;
110. params[3].num = 1;

112. params[4].buffer_type = TSDB_DATA_TYPE_INT;
113. params[4].buffer_length = sizeof(v.v4);
114. params[4].buffer = &v.v4;
115. params[4].length = &intLen;
116. params[4].is_null = NULL;
117. params[4].num = 1;

119. params[5].buffer_type = TSDB_DATA_TYPE_BIGINT;
120. params[5].buffer_length = sizeof(v.v8);
121. params[5].buffer = &v.v8;
122. params[5].length = &bintLen;
123. params[5].is_null = NULL;
124. params[5].num = 1;

126. params[6].buffer_type = TSDB_DATA_TYPE_FLOAT;
127. params[6].buffer_length = sizeof(v.f4);
128. params[6].buffer = &v.f4;
129. params[6].length = &floatLen;
130. params[6].is_null = NULL;
131. params[6].num = 1;

133. params[7].buffer_type = TSDB_DATA_TYPE_DOUBLE;
134. params[7].buffer_length = sizeof(v.f8);
135. params[7].buffer = &v.f8;
136. params[7].length = &doubleLen;
137. params[7].is_null = NULL;
138. params[7].num = 1;

140. params[8].buffer_type = TSDB_DATA_TYPE_BINARY;
141. params[8].buffer_length = sizeof(v.bin);
142. params[8].buffer = v.bin;
143. params[8].length = &binLen;
144. params[8].is_null = NULL;
145. params[8].num = 1;

147. strcpy(v.blob, "一二三四五六七八九十");
148. params[9].buffer_type = TSDB_DATA_TYPE_NCHAR;
149. params[9].buffer_length = sizeof(v.blob);
150. params[9].buffer = v.blob;
151. params[9].length = &ncharLen;
152. params[9].is_null = NULL;
153. params[9].num = 1;

155. char is_null = 1;

157. sql = "insert into m1 values(?,?,?,?,?,?,?,?,?,?)";
158. code = taos_stmt_prepare(stmt, sql, 0);
159. if (code != 0){
160. printf("failed to execute taos_stmt_prepare. code:0x%x\n", code);
161. }
162. v.ts = 1591060628000;
163. for (int i = 0; i < 10; ++i) {
164. v.ts += 1;
165. for (int j = 1; j < 10; ++j) {
166. params[j].is_null = ((i == j) ? &is_null : 0);
167. }
168. v.b = (int8_t)i % 2;
169. v.v1 = (int8_t)i;
170. v.v2 = (int16_t)(i * 2);
171. v.v4 = (int32_t)(i * 4);
172. v.v8 = (int64_t)(i * 8);
173. v.f4 = (float)(i * 40);
174. v.f8 = (double)(i * 80);
175. for (int j = 0; j < sizeof(v.bin); ++j) {
176. v.bin[j] = (char)(i + '0');
177. }

179. taos_stmt_bind_param(stmt, params);
180. taos_stmt_add_batch(stmt);
181. }
182. if (taos_stmt_execute(stmt) != 0) {
183. printf("failed to execute insert statement.\n");
184. exit(1);
185. }
186. taos_stmt_close(stmt);

188. // query the records
189. stmt = taos_stmt_init(taos);
190. taos_stmt_prepare(stmt, "SELECT * FROM m1 WHERE v1 > ? AND v2 < ?", 0);
191. v.v1 = 5;
192. v.v2 = 15;
193. taos_stmt_bind_param(stmt, params + 2);
194. if (taos_stmt_execute(stmt) != 0) {
195. printf("failed to execute select statement.\n");
196. exit(1);
197. }

199. result = taos_stmt_use_result(stmt);

201. TAOS_ROW    row;
202. int         rows = 0;
203. int         num_fields = taos_num_fields(result);
204. TAOS_FIELD *fields = taos_fetch_fields(result);

206. // fetch the records row by row
207. while ((row = taos_fetch_row(result))) {
208. char temp[256] = {0};
209. rows++;
210. taos_print_row(temp, row, fields, num_fields);
211. printf("%s\n", temp);
212. }
213. if (rows == 2) {
214. printf("two rows are fetched as expectation\n");
215. } else {
216. printf("expect two rows, but %d rows are fetched\n", rows);
217. }

219. taos_free_result(result);
220. taos_stmt_close(stmt);

222. return 0;
223. }

查看源码

无模式写入示例

无模式写入

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>

11. int numSuperTables = 8;
12. int numChildTables = 4;
13. int numRowsPerChildTable = 2048;

15. static int64_t getTimeInUs() {
16. struct timeval systemTime;
17. gettimeofday(&systemTime, NULL);
18. return (int64_t)systemTime.tv_sec * 1000000L + (int64_t)systemTime.tv_usec;
19. }

21. int main(int argc, char* argv[]) {
22. TAOS_RES *result;
23. const char* host = "127.0.0.1";
24. const char* user = "root";
25. const char* passwd = "taosdata";

27. taos_options(TSDB_OPTION_TIMEZONE, "GMT-8");
28. TAOS* taos = taos_connect(host, user, passwd, "", 0);
29. if (taos == NULL) {
30. printf("\033[31mfailed to connect to db, reason:%s\033[0m\n", taos_errstr(taos));
31. exit(1);
32. }

34. const char* info = taos_get_server_info(taos);
35. printf("server info: %s\n", info);
36. info = taos_get_client_info(taos);
37. printf("client info: %s\n", info);
38. result = taos_query(taos, "drop database if exists db;");
39. taos_free_result(result);
40. usleep(100000);
41. result = taos_query(taos, "create database db precision 'ms';");
42. taos_free_result(result);
43. usleep(100000);

45. (void)taos_select_db(taos, "db");

47. time_t ct = time(0);
48. int64_t ts = ct * 1000;
49. 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;

51. int lineNum = numSuperTables * numChildTables * numRowsPerChildTable;
52. char** lines = calloc((size_t)lineNum, sizeof(char*));
53. int l = 0;
54. for (int i = 0; i < numSuperTables; ++i) {
55. for (int j = 0; j < numChildTables; ++j) {
56. for (int k = 0; k < numRowsPerChildTable; ++k) {
57. char* line = calloc(512, 1);
58. snprintf(line, 512, lineFormat, i, j, ts + 10 * l);
59. lines[l] = line;
60. ++l;
61. }
62. }
63. }

65. printf("%s\n", "begin taos_insert_lines");
66. int64_t  begin = getTimeInUs();
67. TAOS_RES *res = taos_schemaless_insert(taos, lines, lineNum, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_MILLI_SECONDS);
68. int64_t end = getTimeInUs();
69. printf("code: %s. time used: %" PRId64 "\n", taos_errstr(res), end-begin);
70. taos_free_result(res);

72. return 0;
73. }

查看源码

订阅和消费示例

订阅和消费

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. */

16. #include <assert.h>
17. #include <stdio.h>
18. #include <stdlib.h>
19. #include <string.h>
20. #include <time.h>
21. #include "taos.h"

23. static int running = 1;

25. static int32_t msg_process(TAOS_RES* msg) {
26. char    buf[1024];
27. int32_t rows = 0;

29. const char* topicName = tmq_get_topic_name(msg);
30. const char* dbName = tmq_get_db_name(msg);
31. int32_t     vgroupId = tmq_get_vgroup_id(msg);

33. printf("topic: %s\n", topicName);
34. printf("db: %s\n", dbName);
35. printf("vgroup id: %d\n", vgroupId);

37. while (1) {
38. TAOS_ROW row = taos_fetch_row(msg);
39. if (row == NULL) break;

41. TAOS_FIELD* fields = taos_fetch_fields(msg);
42. int32_t     numOfFields = taos_field_count(msg);
43. // int32_t*    length = taos_fetch_lengths(msg);
44. int32_t precision = taos_result_precision(msg);
45. rows++;
46. taos_print_row(buf, row, fields, numOfFields);
47. printf("precision: %d, row content: %s\n", precision, buf);
48. }

50. return rows;
51. }

53. static int32_t init_env() {
54. TAOS* pConn = taos_connect("localhost", "root", "taosdata", NULL, 0);
55. if (pConn == NULL) {
56. return -1;
57. }

59. TAOS_RES* pRes;
60. // drop database if exists
61. printf("create database\n");
62. pRes = taos_query(pConn, "drop topic topicname");
63. if (taos_errno(pRes) != 0) {
64. printf("error in drop topicname, reason:%s\n", taos_errstr(pRes));
65. }
66. taos_free_result(pRes);

68. pRes = taos_query(pConn, "drop database if exists tmqdb");
69. if (taos_errno(pRes) != 0) {
70. printf("error in drop tmqdb, reason:%s\n", taos_errstr(pRes));
71. }
72. taos_free_result(pRes);

74. // create database
75. pRes = taos_query(pConn, "create database tmqdb precision 'ns'");
76. if (taos_errno(pRes) != 0) {
77. printf("error in create tmqdb, reason:%s\n", taos_errstr(pRes));
78. goto END;
79. }
80. taos_free_result(pRes);

82. // create super table
83. printf("create super table\n");
84. pRes = taos_query(
85. pConn, "create table tmqdb.stb (ts timestamp, c1 int, c2 float, c3 varchar(16)) tags(t1 int, t3 varchar(16))");
86. if (taos_errno(pRes) != 0) {
87. printf("failed to create super table stb, reason:%s\n", taos_errstr(pRes));
88. goto END;
89. }
90. taos_free_result(pRes);

92. // create sub tables
93. printf("create sub tables\n");
94. pRes = taos_query(pConn, "create table tmqdb.ctb0 using tmqdb.stb tags(0, 'subtable0')");
95. if (taos_errno(pRes) != 0) {
96. printf("failed to create super table ctb0, reason:%s\n", taos_errstr(pRes));
97. goto END;
98. }
99. taos_free_result(pRes);

101. pRes = taos_query(pConn, "create table tmqdb.ctb1 using tmqdb.stb tags(1, 'subtable1')");
102. if (taos_errno(pRes) != 0) {
103. printf("failed to create super table ctb1, reason:%s\n", taos_errstr(pRes));
104. goto END;
105. }
106. taos_free_result(pRes);

108. pRes = taos_query(pConn, "create table tmqdb.ctb2 using tmqdb.stb tags(2, 'subtable2')");
109. if (taos_errno(pRes) != 0) {
110. printf("failed to create super table ctb2, reason:%s\n", taos_errstr(pRes));
111. goto END;
112. }
113. taos_free_result(pRes);

115. pRes = taos_query(pConn, "create table tmqdb.ctb3 using tmqdb.stb tags(3, 'subtable3')");
116. if (taos_errno(pRes) != 0) {
117. printf("failed to create super table ctb3, reason:%s\n", taos_errstr(pRes));
118. goto END;
119. }
120. taos_free_result(pRes);

122. // insert data
123. printf("insert data into sub tables\n");
124. pRes = taos_query(pConn, "insert into tmqdb.ctb0 values(now, 0, 0, 'a0')(now+1s, 0, 0, 'a00')");
125. if (taos_errno(pRes) != 0) {
126. printf("failed to insert into ctb0, reason:%s\n", taos_errstr(pRes));
127. goto END;
128. }
129. taos_free_result(pRes);

131. pRes = taos_query(pConn, "insert into tmqdb.ctb1 values(now, 1, 1, 'a1')(now+1s, 11, 11, 'a11')");
132. if (taos_errno(pRes) != 0) {
133. printf("failed to insert into ctb0, reason:%s\n", taos_errstr(pRes));
134. goto END;
135. }
136. taos_free_result(pRes);

138. pRes = taos_query(pConn, "insert into tmqdb.ctb2 values(now, 2, 2, 'a1')(now+1s, 22, 22, 'a22')");
139. if (taos_errno(pRes) != 0) {
140. printf("failed to insert into ctb0, reason:%s\n", taos_errstr(pRes));
141. goto END;
142. }
143. taos_free_result(pRes);

145. pRes = taos_query(pConn, "insert into tmqdb.ctb3 values(now, 3, 3, 'a1')(now+1s, 33, 33, 'a33')");
146. if (taos_errno(pRes) != 0) {
147. printf("failed to insert into ctb0, reason:%s\n", taos_errstr(pRes));
148. goto END;
149. }
150. taos_free_result(pRes);
151. taos_close(pConn);
152. return 0;

154. END:
155. taos_free_result(pRes);
156. taos_close(pConn);
157. return -1;
158. }

160. int32_t create_topic() {
161. printf("create topic\n");
162. TAOS_RES* pRes;
163. TAOS*     pConn = taos_connect("localhost", "root", "taosdata", NULL, 0);
164. if (pConn == NULL) {
165. return -1;
166. }

168. pRes = taos_query(pConn, "use tmqdb");
169. if (taos_errno(pRes) != 0) {
170. printf("error in use tmqdb, reason:%s\n", taos_errstr(pRes));
171. return -1;
172. }
173. taos_free_result(pRes);

175. pRes = taos_query(pConn, "create topic topicname as select ts, c1, c2, c3, tbname from tmqdb.stb where c1 > 1");
176. if (taos_errno(pRes) != 0) {
177. printf("failed to create topic topicname, reason:%s\n", taos_errstr(pRes));
178. return -1;
179. }
180. taos_free_result(pRes);

182. taos_close(pConn);
183. return 0;
184. }

186. void tmq_commit_cb_print(tmq_t* tmq, int32_t code, void* param) {
187. printf("tmq_commit_cb_print() code: %d, tmq: %p, param: %p\n", code, tmq, param);
188. }

190. tmq_t* build_consumer() {
191. tmq_conf_res_t code;
192. tmq_t*         tmq = NULL;

194. tmq_conf_t* conf = tmq_conf_new();
195. code = tmq_conf_set(conf, "enable.auto.commit", "true");
196. if (TMQ_CONF_OK != code) {
197. tmq_conf_destroy(conf);
198. return NULL;
199. }
200. code = tmq_conf_set(conf, "auto.commit.interval.ms", "1000");
201. if (TMQ_CONF_OK != code) {
202. tmq_conf_destroy(conf);
203. return NULL;
204. }
205. code = tmq_conf_set(conf, "group.id", "cgrpName");
206. if (TMQ_CONF_OK != code) {
207. tmq_conf_destroy(conf);
208. return NULL;
209. }
210. code = tmq_conf_set(conf, "client.id", "user defined name");
211. if (TMQ_CONF_OK != code) {
212. tmq_conf_destroy(conf);
213. return NULL;
214. }
215. code = tmq_conf_set(conf, "td.connect.user", "root");
216. if (TMQ_CONF_OK != code) {
217. tmq_conf_destroy(conf);
218. return NULL;
219. }
220. code = tmq_conf_set(conf, "td.connect.pass", "taosdata");
221. if (TMQ_CONF_OK != code) {
222. tmq_conf_destroy(conf);
223. return NULL;
224. }
225. code = tmq_conf_set(conf, "auto.offset.reset", "earliest");
226. if (TMQ_CONF_OK != code) {
227. tmq_conf_destroy(conf);
228. return NULL;
229. }
230. code = tmq_conf_set(conf, "experimental.snapshot.enable", "false");
231. if (TMQ_CONF_OK != code) {
232. tmq_conf_destroy(conf);
233. return NULL;
234. }

236. tmq_conf_set_auto_commit_cb(conf, tmq_commit_cb_print, NULL);
237. tmq = tmq_consumer_new(conf, NULL, 0);

239. _end:
240. tmq_conf_destroy(conf);
241. return tmq;
242. }

244. tmq_list_t* build_topic_list() {
245. tmq_list_t* topicList = tmq_list_new();
246. int32_t     code = tmq_list_append(topicList, "topicname");
247. if (code) {
248. tmq_list_destroy(topicList);
249. return NULL;
250. }
251. return topicList;
252. }

254. void basic_consume_loop(tmq_t* tmq) {
255. int32_t totalRows = 0;
256. int32_t msgCnt = 0;
257. int32_t timeout = 5000;
258. while (running) {
259. TAOS_RES* tmqmsg = tmq_consumer_poll(tmq, timeout);
260. if (tmqmsg) {
261. msgCnt++;
262. totalRows += msg_process(tmqmsg);
263. taos_free_result(tmqmsg);
264. } else {
265. break;
266. }
267. }

269. fprintf(stderr, "%d msg consumed, include %d rows\n", msgCnt, totalRows);
270. }

272. int main(int argc, char* argv[]) {
273. int32_t code;

275. if (init_env() < 0) {
276. return -1;
277. }

279. if (create_topic() < 0) {
280. return -1;
281. }

283. tmq_t* tmq = build_consumer();
284. if (NULL == tmq) {
285. fprintf(stderr, "build_consumer() fail!\n");
286. return -1;
287. }

289. tmq_list_t* topic_list = build_topic_list();
290. if (NULL == topic_list) {
291. return -1;
292. }

294. if ((code = tmq_subscribe(tmq, topic_list))) {
295. fprintf(stderr, "Failed to tmq_subscribe(): %s\n", tmq_err2str(code));
296. }
297. tmq_list_destroy(topic_list);

299. basic_consume_loop(tmq);

301. code = tmq_consumer_close(tmq);
302. if (code) {
303. fprintf(stderr, "Failed to close consumer: %s\n", tmq_err2str(code));
304. } else {
305. fprintf(stderr, "Consumer closed\n");
306. }

308. return 0;
309. }

查看源码

C/C++ - 图2info

更多示例代码及下载请见 GitHub。 也可以在安装目录下的 examples/c 路径下找到。 该目录下有 makefile,在 Linux/macOS 环境下,直接执行 make 就可以编译得到执行文件。 提示:在 ARM 环境下编译时,请将 makefile 中的 -msse4.2 去掉,这个选项只有在 x64/x86 硬件平台上才能支持。

API 参考

以下分别介绍 TDengine 客户端驱动的基础 API、同步 API、异步 API、订阅 API 和无模式写入 API。

基础 API

基础 API 用于完成创建数据库连接等工作,为其它 API 的执行提供运行时环境。

  • void taos_init()

初始化运行环境。如果没有主动调用该 API,那么调用 taos_connect() 时驱动将自动调用该 API,故程序一般无需手动调用。 - void taos_cleanup()

清理运行环境,应用退出前应调用。 - int taos_options(TSDB_OPTION option, const void * arg, ...)

设置客户端选项,目前支持区域设置(TSDB_OPTION_LOCALE)、字符集设置(TSDB_OPTION_CHARSET)、时区设置(TSDB_OPTION_TIMEZONE)、配置文件路径设置(TSDB_OPTION_CONFIGDIR)。区域设置、字符集、时区默认为操作系统当前设置。 - char *taos_get_client_info()

获取客户端版本信息。 - TAOS *taos_connect(const char *host, const char *user, const char *pass, const char *db, int port)

创建数据库连接,初始化连接上下文。其中需要用户提供的参数包含:

  • host:TDengine 集群中任一节点的 FQDN
  • user:用户名
  • pass:密码
  • db: 数据库名字,如果用户没有提供,也可以正常连接,用户可以通过该连接创建新的数据库,如果用户提供了数据库名字,则说明该数据库用户已经创建好,缺省使用该数据库
  • port:taosd 程序监听的端口

返回值为空表示失败。应用程序需要保存返回的参数,以便后续使用。

##### C/C++ - 图3info

同一进程可以根据不同的 host/port 连接多个 TDengine 集群 - char *taos_get_server_info(TAOS *taos)

获取服务端版本信息。 - int taos_select_db(TAOS *taos, const char *db)

将当前的缺省数据库设置为 db。 - int taos_get_current_db(TAOS *taos, char *database, int len, int *required)

  • database,len为用户在外面申请的空间,内部会把当前db赋值到database里。
  • 只要是没有正常把db名赋值到database中(包括截断),返回错误,返回值为-1,然后用户可以通过 taos_errstr(NULL) 来获取错误提示。
  • 如果,database == NULL 或者 len<=0 返回错误,required里保存存储db需要的空间(包含最后的’\0’)
  • 如果,len 小于 存储db需要的空间(包含最后的’\0’),返回错误,database里赋值截断的数据,以’\0’结尾。
  • 如果,len 大于等于 存储db需要的空间(包含最后的’\0’),返回正常0,database里赋值以’\0‘结尾的db名。
  • void taos_close(TAOS *taos)

关闭连接,其中taos是 taos_connect() 返回的句柄。

同步查询 API

本小节介绍 API 均属于同步接口。应用调用后,会阻塞等待响应,直到获得返回结果或错误信息。

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

执行 SQL 语句,可以是 DQL、DML 或 DDL 语句。 其中的 taos 参数是通过 taos_connect() 获得的句柄。不能通过返回值是否是 NULL 来判断执行结果是否失败,而是需要用 taos_errno() 函数解析结果集中的错误代码来进行判断。 - int taos_result_precision(TAOS_RES *res)

返回结果集时间戳字段的精度,0 代表毫秒,1 代表微秒,2 代表纳秒。 - TAOS_ROW taos_fetch_row(TAOS_RES *res)

按行获取查询结果集中的数据。 - int taos_fetch_block(TAOS_RES *res, TAOS_ROW *rows)

批量获取查询结果集中的数据,返回值为获取到的数据的行数。 - int taos_num_fields(TAOS_RES *res) 和 int taos_field_count(TAOS_RES *res)

这两个 API 等价,用于获取查询结果集中的列数。 - int* taos_fetch_lengths(TAOS_RES *res)

获取结果集中每个字段的长度。返回值是一个数组,其长度为结果集的列数。 - int taos_affected_rows(TAOS_RES *res)

获取被所执行的 SQL 语句影响的行数。 - TAOS_FIELD *taos_fetch_fields(TAOS_RES *res)

获取查询结果集每列数据的属性(列的名称、列的数据类型、列的长度),与 taos_num_fields() 配合使用,可用来解析 taos_fetch_row() 返回的一个元组(一行)的数据。 TAOS_FIELD 的结构如下:

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)

停止当前查询的执行。 - void taos_free_result(TAOS_RES *res)

释放查询结果集以及相关的资源。查询完成后,务必调用该 API 释放资源,否则可能导致应用内存泄露。但也需注意,释放资源后,如果再调用 taos_consume() 等获取查询结果的函数,将导致应用崩溃。 - char *taos_errstr(TAOS_RES *res)

获取最近一次 API 调用失败的原因,返回值为字符串标识的错误提示信息。 - int taos_errno(TAOS_RES *res)

获取最近一次 API 调用失败的原因,返回值为错误代码。

C/C++ - 图4note

2.0 及以上版本 TDengine 推荐数据库应用的每个线程都建立一个独立的连接,或基于线程建立连接池。而不推荐在应用中将该连接 (TAOS*) 结构体传递到不同的线程共享使用。基于 TAOS 结构体发出的查询、写入等操作具有多线程安全性,但 “USE statement” 等状态量有可能在线程之间相互干扰。此外,C 语言的连接器可以按照需求动态建立面向数据库的新连接(该过程对用户不可见),同时建议只有在程序最后退出的时候才调用 taos_close() 关闭连接。 另一个需要注意的是,在上述同步 API 执行过程中,不能调用类似 pthread_cancel 之类的 API 来强制结束线程,因为涉及一些模块的同步操作,如果强制结束线程有可能造成包括但不限于死锁等异常状况。

异步查询 API

TDengine 还提供性能更高的异步 API 处理数据插入、查询操作。在软硬件环境相同的情况下,异步 API 处理数据插入的速度比同步 API 快 2 ~ 4 倍。异步 API 采用非阻塞式的调用方式,在系统真正完成某个具体数据库操作前,立即返回。调用的线程可以去处理其他工作,从而可以提升整个应用的性能。异步 API 在网络延迟严重的情况下,优势尤为突出。

异步 API 都需要应用提供相应的回调函数,回调函数参数设置如下:前两个参数都是一致的,第三个参数依不同的 API 而定。第一个参数 param 是应用调用异步 API 时提供给系统的,用于回调时,应用能够找回具体操作的上下文,依具体实现而定。第二个参数是 SQL 操作的结果集,如果为空,比如 insert 操作,表示没有记录返回,如果不为空,比如 select 操作,表示有记录返回。

异步 API 对于使用者的要求相对较高,用户可根据具体应用场景选择性使用。下面是两个重要的异步 API:

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

异步执行 SQL 语句。

  • taos:调用 taos_connect() 返回的数据库连接
  • sql:需要执行的 SQL 语句
  • fp:用户定义的回调函数,其第三个参数 code 用于指示操作是否成功,0 表示成功,负数表示失败(调用 taos_errstr() 可获取失败原因)。应用在定义回调函数的时候,主要处理第二个参数 TAOS_RES *,该参数是查询返回的结果集
  • param:应用提供一个用于回调的参数
  • void taos_fetch_rows_a(TAOS_RES *res, void (*fp)(void *param, TAOS_RES *, int numOfRows), void *param);

批量获取异步查询的结果集,只能与 taos_query_a() 配合使用。其中:

  • res:taos_query_a() 回调时返回的结果集
  • fp:回调函数。其参数 param 是用户可定义的传递给回调函数的参数结构体;numOfRows 是获取到的数据的行数(不是整个查询结果集的函数)。 在回调函数中,应用可以通过调用 taos_fetch_row() 前向迭代获取批量记录中每一行记录。读完一块内的所有记录后,应用需要在回调函数中继续调用 taos_fetch_rows_a() 获取下一批记录进行处理,直到返回的记录数 numOfRows 为零(结果返回完成)或记录数为负值(查询出错)。

TDengine 的异步 API 均采用非阻塞调用模式。应用程序可以用多线程同时打开多张表,并可以同时对每张打开的表进行查询或者插入操作。需要指出的是,客户端应用必须确保对同一张表的操作完全串行化,即对同一个表的插入或查询操作未完成时(未返回时),不能够执行第二个插入或查询操作。

参数绑定 API

除了直接调用 taos_query() 进行查询,TDengine 也提供了支持参数绑定的 Prepare API,风格与 MySQL 类似,目前也仅支持用问号 ? 来代表待绑定的参数。

从 2.1.1.0 和 2.1.2.0 版本开始,TDengine 大幅改进了参数绑定接口对数据写入(INSERT)场景的支持。这样在通过参数绑定接口写入数据时,就避免了 SQL 语法解析的资源消耗,从而在绝大多数情况下显著提升写入性能。此时的典型操作步骤如下:

  1. 调用 taos_stmt_init() 创建参数绑定对象;
  2. 调用 taos_stmt_prepare() 解析 INSERT 语句;
  3. 如果 INSERT 语句中预留了表名但没有预留 TAGS,那么调用 taos_stmt_set_tbname() 来设置表名;
  4. 如果 INSERT 语句中既预留了表名又预留了 TAGS(例如 INSERT 语句采取的是自动建表的方式),那么调用 taos_stmt_set_tbname_tags() 来设置表名和 TAGS 的值;
  5. 调用 taos_stmt_bind_param_batch() 以多行的方式设置 VALUES 的值,或者调用 taos_stmt_bind_param() 以单行的方式设置 VALUES 的值;
  6. 调用 taos_stmt_add_batch() 把当前绑定的参数加入批处理;
  7. 可以重复第 3 ~ 6 步,为批处理加入更多的数据行;
  8. 调用 taos_stmt_execute() 执行已经准备好的批处理指令;
  9. 执行完毕,调用 taos_stmt_close() 释放所有资源。

说明:如果 taos_stmt_execute() 执行成功,假如不需要改变 SQL 语句的话,那么是可以复用 taos_stmt_prepare() 的解析结果,直接进行第 3 ~ 6 步绑定新数据的。但如果执行出错,那么并不建议继续在当前的环境上下文下继续工作,而是建议释放资源,然后从 taos_stmt_init() 步骤重新开始。

接口相关的具体函数如下(也可以参考 prepare.c 文件中使用对应函数的方式):

  • TAOS_STMT* taos_stmt_init(TAOS *taos)

创建一个 TAOS_STMT 对象用于后续调用。 - int taos_stmt_prepare(TAOS_STMT *stmt, const char *sql, unsigned long length)

解析一条 SQL 语句,将解析结果和参数信息绑定到 stmt 上,如果参数 length 大于 0,将使用此参数作为 SQL 语句的长度,如等于 0,将自动判断 SQL 语句的长度。 - int taos_stmt_bind_param(TAOS_STMT *stmt, TAOS_BIND *bind)

不如 taos_stmt_bind_param_batch() 效率高,但可以支持非 INSERT 类型的 SQL 语句。 进行参数绑定,bind 指向一个数组(代表所要绑定的一行数据),需保证此数组中的元素数量和顺序与 SQL 语句中的参数完全一致。TAOS_BIND 的使用方法与 MySQL 中的 MYSQL_BIND 类似,具体定义如下:

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)

(2.1.1.0 版本新增,仅支持用于替换 INSERT 语句中的参数值) 当 SQL 语句中的表名使用了 ? 占位时,可以使用此函数绑定一个具体的表名。 - int taos_stmt_set_tbname_tags(TAOS_STMT* stmt, const char* name, TAOS_BIND* tags)

(2.1.2.0 版本新增,仅支持用于替换 INSERT 语句中的参数值) 当 SQL 语句中的表名和 TAGS 都使用了 ? 占位时,可以使用此函数绑定具体的表名和具体的 TAGS 取值。最典型的使用场景是使用了自动建表功能的 INSERT 语句(目前版本不支持指定具体的 TAGS 列)。TAGS 参数中的列数量需要与 SQL 语句中要求的 TAGS 数量完全一致。 - int taos_stmt_bind_param_batch(TAOS_STMT* stmt, TAOS_MULTI_BIND* bind)

(2.1.1.0 版本新增,仅支持用于替换 INSERT 语句中的参数值) 以多列的方式传递待绑定的数据,需要保证这里传递的数据列的顺序、列的数量与 SQL 语句中的 VALUES 参数完全一致。TAOS_MULTI_BIND 的具体定义如下:

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)

将当前绑定的参数加入批处理中,调用此函数后,可以再次调用 taos_stmt_bind_param() 或 taos_stmt_bind_param_batch() 绑定新的参数。需要注意,此函数仅支持 INSERT/IMPORT 语句,如果是 SELECT 等其他 SQL 语句,将返回错误。 - int taos_stmt_execute(TAOS_STMT *stmt)

执行准备好的语句。目前,一条语句只能执行一次。 - TAOS_RES* taos_stmt_use_result(TAOS_STMT *stmt)

获取语句的结果集。结果集的使用方式与非参数化调用时一致,使用完成后,应对此结果集调用 taos_free_result() 以释放资源。 - int taos_stmt_close(TAOS_STMT *stmt)

执行完毕,释放所有资源。 - char * taos_stmt_errstr(TAOS_STMT *stmt)

(2.1.3.0 版本新增) 用于在其他 STMT API 返回错误(返回错误码或空指针)时获取错误信息。

无模式(schemaless)写入 API

除了使用 SQL 方式或者使用参数绑定 API 写入数据外,还可以使用 Schemaless 的方式完成写入。Schemaless 可以免于预先创建超级表/数据子表的数据结构,而是可以直接写入数据,TDengine 系统会根据写入的数据内容自动创建和维护所需要的表结构。Schemaless 的使用方式详见 Schemaless 写入 章节,这里介绍与之配套使用的 C/C++ API。

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

功能说明 该接口将行协议的文本数据写入到 TDengine 中。

参数说明 taos: 数据库连接,通过 taos_connect() 函数建立的数据库连接。 lines:文本数据。满足解析格式要求的无模式文本字符串。 numLines:文本数据的行数,不能为 0 。 protocol: 行协议类型,用于标识文本数据格式。 precision:文本数据中的时间戳精度字符串。

返回值 TAOS_RES 结构体,应用可以通过使用 taos_errstr() 获得错误信息,也可以使用 taos_errno() 获得错误码。 在某些情况下,返回的 TAOS_RES 为 NULL,此时仍然可以调用 taos_errno() 来安全地获得错误码信息。 返回的 TAOS_RES 需要调用方来负责释放,否则会出现内存泄漏。

说明 协议类型是枚举类型,包含以下三种格式:

  • TSDB_SML_LINE_PROTOCOL:InfluxDB 行协议(Line Protocol)
  • TSDB_SML_TELNET_PROTOCOL: OpenTSDB Telnet 文本行协议
  • TSDB_SML_JSON_PROTOCOL: OpenTSDB Json 协议格式

时间戳分辨率的定义,定义在 taos.h 文件中,具体内容如下:

  • 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

需要注意的是,时间戳分辨率参数只在协议类型为 SML_LINE_PROTOCOL 的时候生效。 对于 OpenTSDB 的文本协议,时间戳的解析遵循其官方解析规则 — 按照时间戳包含的字符的数量来确认时间精度。

schemaless 其他相关的接口 - TAOS_RES *taos_schemaless_insert_with_reqid(TAOS *taos, char *lines[], int numLines, int protocol, int precision, int64_t reqid) - TAOS_RES *taos_schemaless_insert_raw(TAOS *taos, char *lines, int len, int32_t *totalRows, int protocol, int precision) - TAOS_RES *taos_schemaless_insert_raw_with_reqid(TAOS *taos, char *lines, int len, int32_t *totalRows, int protocol, int precision, int64_t reqid) - `TAOS_RES taos_schemaless_insert_ttl(TAOS taos, char *lines[], int numLines, int protocol, int precision, int32_t t

(本文超出站点单文档体积上限,已截断)