未验证 提交 b697253b 编写于 作者: sangshuduo's avatar sangshuduo 提交者: GitHub

docs: connector doc in English (#12511)

* docs: connector in English

[TD-15544]

* docs: connector doc in English

[TD-15544]
上级 666ec340
---
title: 连接器
--
title: Connector
---
TDengine 提供了丰富的应用程序开发接口,为了便于用户快速开发自己的应用,TDengine 支持了多种编程语言的连接器,其中官方连接器包括支持 C/C++、Java、Python、Go、Node.js、C# 和 Rust 的连接器。这些连接器支持使用原生接口(taosc)和 REST 接口(部分语言暂不支持)连接 TDengine 集群。社区开发者也贡献了多个非官方连接器,例如 ADO.NET 连接器、Lua 连接器和 PHP 连接器。
TDengine provides a rich application development interface. To facilitate users to develop their own applications quickly, TDengine supports connectors for multiple programming languages, including official connectors for C/C++, Java, Python, Go, Node.js, C#, and Rust. These connectors support connecting to TDengine clusters using both native interfaces (taosc) and REST interfaces (not supported in some languages yet). Community developers have also contributed several unofficial connectors, such as the ADO.NET connector, the Lua connector, and the PHP connector.
![image-connector](/img/connector.png)
! [image-connector](/img/connector.png)
## 支持的平台
## Supported platforms
目前 TDengine 的原生接口连接器可支持的平台包括:X64/X86/ARM64/ARM32/MIPS/Alpha 等硬件平台,以及 Linux/Win64/Win32 等开发环境。对照矩阵如下:
Currently, TDengine's native interface connectors can support platforms such as X64/X86/ARM64/ARM32/MIPS/Alpha hardware platforms and Linux/Win64/Win32 development environments. The comparison matrix is as follows.
| **CPU** | **OS** | **JDBC** | **Python** | **Go** | **Node.js** | **C#** | **Rust** | C/C++ |
| **CPU** | **OS** | **JDBC** | **Python** | **Go** | **Node.js** | **C#** | **Rust** | C/C++ |
| -------------- | --------- | -------- | ---------- | ------ | ----------- | ------ | -------- | ----- |
| **X86 64bit** | **Linux** | ● | ● | ● | ● | ● | ● | ● |
| **X86 64bit** | **Win64** | ● | ● | ● | ● | ● | ● | ● |
| **X86 64bit** | **Win32** | ● | ● | ● | ● | ○ | ○ | ● |
| **X86 32bit** | **Win32** | ○ | ○ | ○ | ○ | ○ | ○ | ● |
| **ARM64** | **Linux** | ● | ● | ● | ● | ○ | ○ | ● |
| **ARM32** | **Linux** | ● | ● | ● | ● | ○ | ○ | ● |
| **MIPS 龙芯** | **Linux** | ○ | ○ | ○ | ○ | ○ | ○ | ○ |
| **Alpha 申威** | **Linux** | ○ | ○ | -- | -- | -- | -- | ○ |
| **X86 海光** | **Linux** | ○ | ○ | ○ | -- | -- | -- | ○ |
| | **X86 64bit** | **Linux** | ● | ● | ● | ● | ● | ● | ● | ●
| **X86 64bit** | **Win64** | ● | ● | ● | ● | ● | ● | ● | ●
| **X86 64bit** | **Win32** | ● | ● ● | ○ | ○ | ●
| **X86 32bit** | **Win32** | ○ | ○ | ○ | ○ | ○ | ●
| **ARM64** | **Linux** | ● | ● ● | ○ | ○ | ●
| **ARM32** | **Linux** | ● ● ● ● ● ● | ○ | ○ | ●
| **MIPS Longcore** | **Linux** | ○ | ○ | ○ | ○ | ○ | ○ | ○
| **Alpha Shenwei** | **Linux** | ○ | ○ ○ | -- | -- | --- | --- | ○ |
| **X86 Haiguang** | **Linux** | ○ | ○ | ○ | -- | -- | --- | ○ |
其中 ● 表示官方测试验证通过,○ 表示非官方测试验证通过,-- 表示未经验证。
Where ● means the official test verification passed, ○ means the unofficial test verification passed, -- means no assurance.
使用 REST 连接由于不依赖客户端驱动可以支持更广泛的操作系统。
Using REST connection can support a broader range of operating systems as it does not rely on client drivers.
## 版本支持
## Version support
TDengine 版本更新往往会增加新的功能特性,列表中的连接器版本为连接器最佳适配版本。
TDengine version updates often add new features, and the connector versions in the list are the best-fit versions of the connector.
| **TDengine 版本** | **Java** | **Python** | **Go** | **C#** | **Node.js** | **Rust** |
| **TDengine Versions** | **Java** | **Python** | **Go** | **C#** | **Node.js** | **Rust** |
| --------------------- | -------- | ---------- | ------------ | ------------- | --------------- | -------- |
| **2.4.0.14 及以上** | 2.0.38 | 当前版本 | develop 分支 | 1.0.2 - 1.0.6 | 2.0.10 - 2.0.12 | 当前版本 |
| **2.4.0.6 及以上** | 2.0.37 | 当前版本 | develop 分支 | 1.0.2 - 1.0.6 | 2.0.10 - 2.0.12 | 当前版本 |
| **2.4.0.4 - 2.4.0.5** | 2.0.37 | 当前版本 | develop 分支 | 1.0.2 - 1.0.6 | 2.0.10 - 2.0.12 | 当前版本 |
| **2.2.x.x ** | 2.0.36 | 当前版本 | master 分支 | n/a | 2.0.7 - 2.0.9 | 当前版本 |
| **2.0.x.x ** | 2.0.34 | 当前版本 | master 分支 | n/a | 2.0.1 - 2.0.6 | 当前版本 |
| **2.4.0.14 and up** | 2.0.38 | current version | develop branch | 1.0.2 - 1.0.6 | 2.0.10 - 2.0.12 | current version |
| **2.4.0.6 and up** | 2.0.37 | current version | develop branch | 1.0.2 - 1.0.6 | 2.0.10 - 2.0.12 | current version |
| **2.4.0.4 - 2.4.0.5** | 2.0.37 | current version | develop branch | 1.0.2 - 1.0.6 | 2.0.10 - 2.0.12 | current version |
| **2.2.x.x ** | 2.0.36 | current version | master branch | n/a | 2.0.7 - 2.0.9 | current version |
| **2.0.x.x ** | 2.0.34 | current version | master branch | n/a | 2.0.1 - 2.0.6 | current version |
## 功能特性
## Functional Features
连接器对 TDengine 功能特性的支持对照如下:
Comparing the connector support for TDengine functional features as follows.
### 使用原生接口(taosc)
### Using the native interface (taosc)
| **功能特性** | **Java** | **Python** | **Go** | **C#** | **Node.js** | **Rust** |
| **Functional Features** | **Java** | **Python** | **Go** | **C#** | **Node.js** | **Rust** |
| -------------- | -------- | ---------- | ------ | ------ | ----------- | -------- |
| **连接管理** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 |
| **普通查询** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 |
| **连续查询** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 |
| **参数绑定** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 |
| **订阅功能** | 支持 | 支持 | 支持 | 支持 | 支持 | 暂不支持 |
| **Schemaless** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 |
| **DataFrame** | 不支持 | 支持 | 不支持 | 不支持 | 不支持 | 不支持 |
| **Connection Management** | Support | Support | Support | Support | Support | Support | Support
| Support | Support | Support | Support | Support | Support | Support | Support | Support
| Support | Support | Support | Support | Support | Support | Support | Support | Support
| **Parameter Binding** | Support | Support | Support | Support | Support | Support | Support
| Support | Support | Support | Support | Support | Support | Support | Not Supported
| **Schemaless** | Support | Support | Support | Support | Support | Support | Support
| **DataFrame** | Not Supported | Support | Not Supported | Not Supported | Not Supported | Not Supported
:::info
由于不同编程语言数据库框架规范不同,并不意味着所有 C/C++ 接口都需要对应封装支持。
The different database framework specifications for various programming languages do not mean that all C/C++ interfaces need a wrapper.
:::
### 使用 REST 接口
### Using the REST interface
| **功能特性** | **Java** | **Python** | **Go** | **C#(暂不支持)** | **Node.js** | **Rust** |
| **Functional Features** | **Java** | **Python** | **Go** | **C# (not supported yet)** | **Node.js** | **Rust** |
| ------------------------------ | -------- | ---------- | -------- | ------------------ | ----------- | -------- |
| **连接管理** | 支持 | 支持 | 支持 | N/A | 支持 | 支持 |
| **普通查询** | 支持 | 支持 | 支持 | N/A | 支持 | 支持 |
| **连续查询** | 支持 | 支持 | 支持 | N/A | 支持 | 支持 |
| **参数绑定** | 不支持 | 不支持 | 不支持 | N/A | 不支持 | 不支持 |
| **订阅功能** | 不支持 | 不支持 | 不支持 | N/A | 不支持 | 不支持 |
| **Schemaless** | 暂不支持 | 暂不支持 | 暂不支持 | N/A | 暂不支持 | 暂不支持 |
| **批量拉取(基于 WebSocket)** | 支持 | 暂不支持 | 暂不支持 | N/A | 暂不支持 | 暂不支持 |
| **DataFrame** | 不支持 | 支持 | 不支持 | N/A | 不支持 | 不支持 |
| **Connection Management** | Support | Support | Support | N/A | Support | Support | Support
| Support | Support | N/A | Support | Support | Support
| Support | Support | N/A | Support | Support | Support
| Support | N/A | Support | N/A | Support | N/A
| | N/A | Support | N/A | Support | N/A
| **Schemaless** | Not supported | N/A | Not supported | Not supported | N/A
| N/A | Not Supported | Not Supported | N/A
| **DataFrame** | Not supported | Support | Not supported | N/A | Not supported | Not supported
:::warning
- 无论选用何种编程语言的连接器,2.0 及以上版本的 TDengine 推荐数据库应用的每个线程都建立一个独立的连接,或基于线程建立连接池,以避免连接内的“USE statement”状态量在线程之间相互干扰(但连接的查询和写入操作都是线程安全的)。
- Regardless of the programming language chosen for the connector, TDengine versions 2.0 and above recommend that each thread of a database application create a separate connection. Or create a connection pool based on threads to avoid interference between threads with the "USE statement" state within a connection (but the connection's query and write operations are thread-safe).
:::
import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";
import InstallOnWindows from "./_linux_install.mdx";
import InstallOnLinux from "./_windows_install.mdx";
import VerifyWindows from "./_verify_windows.mdx";
import VerifyLinux from "./_verify_linux.mdx";
import InstallOnWindows from ". /_linux_install.mdx";
import InstallOnLinux from ". /_windows_install.mdx";
import VerifyWindows from ". /_verify_windows.mdx";
import VerifyLinux from ". /_verify_linux.mdx";
## 安装客户端驱动
## Install client driver
:::info
只有在没有安装 TDengine 服务端软件的系统上使用原生接口连接器才需要安装客户端驱动。
The client driver needs to be installed if you use the native interface connector on a system that does not have the TDengine server software installed.
:::
### 安装步骤
### Installation steps
<Tabs defaultValue="linux" groupId="os">
<TabItem value="linux" label="Linux">
......@@ -102,9 +102,9 @@ import VerifyLinux from "./_verify_linux.mdx";
</TabItem>
</Tabs>
### 安装验证
### Installation Verification
以上安装和配置完成后,并确认 TDengine 服务已经正常启动运行,此时可以执行 TDengine CLI 工具进行登录。
After completing the above installation and configuration and you have confirmed that the TDengine service is up and running, you can execute the TDengine CLI tool to log in.
<Tabs defaultValue="linux" groupId="os">
<TabItem value="linux" label="Linux">
......
......@@ -27,6 +27,6 @@ import PkgList from "/components/PkgList";
1. If the computer does not run the TDengine service but installs the TDengine application driver, then you need to config `firstEP` in `taos.cfg` only, and there is no need to configure `FQDN`;
2. If you encounter the "Unable to resolve FQDN" error, please make sure the FQDN in the `/etc/hosts` file of the current computer is correctly configured or the DNS service is correctly configured.
2. If you encounter the "Unable to resolve FQDN" error, please make sure the FQDN in the `/etc/hosts` file of the current computer is correctly configured, or the DNS service is correctly configured.
:::
- 已安装客户端驱动(使用原生连接必须安装,使用 REST 连接无需安装)
- Client driver installed (mandatory for native connections, not required for REST connections)
:::info
由于 TDengine 的客户端驱动使用 C 语言编写,使用原生连接时需要加载系统对应安装在本地的客户端驱动共享库文件,通常包含在 TDengine 安装包。TDengine Linux 服务端安装包附带了 TDengine 客户端,也可以单独安装 [Linux 客户端](/get-started/) 。在 Windows 环境开发时需要安装 TDengine 对应的 [Windows 客户端](https://www.taosdata.com/cn/all-downloads/#TDengine-Windows-Client) 。
Since the TDengine client driver is written in C, using the native connection requires loading the client driver shared library file, which is usually included in the TDengine installer. You can install either standard TDengine server installation package or [TDengine client installtion package](/get-started/). For Windows development, you need to install the corresponding [Windows client](https://www.taosdata.com/cn/all-downloads/#TDengine-Windows-Client) for TDengine.
- libtaos.so: 在 Linux 系统中成功安装 TDengine 后,依赖的 Linux 版客户端驱动 libtaos.so 文件会被自动拷贝至 /usr/lib/libtaos.so,该目录包含在 Linux 自动扫描路径上,无需单独指定。
- taos.dll: 在 Windows 系统中安装完客户端之后,依赖的 Windows 版客户端驱动 taos.dll 文件会自动拷贝到系统默认搜索路径 C:/Windows/System32 下,同样无需要单独指定。
- libtaos.so: After successful installation of TDengine on a Linux system, the dependent Linux version of the client driver libtaos.so file will be automatically copied to /usr/lib/libtaos.so, which is included in the Linux scanable path and does not need to be specified separately.
- taos.dll: After installing the client on Windows, the dependent Windows version of the client driver taos.dll file will be automatically copied to the system default search path C:/Windows/System32, again without the need to specify it separately.
:::
在 Linux shell 下直接执行 `taos` 连接到 TDegine 服务,进入到 TDengine CLI 界面,示例如下:
Execute `taos` directly under the Linux shell to connect to the TDengine service and enter the TDengine CLI interface, as shown in the following example.
```text
$ taos
......
在 cmd 下进入到 C:\TDengine 目录下直接执行 `taos.exe`,连接到 TDengine 服务,进入到 TDengine CLI 界面,示例如下:
```text
C:\TDengine>taos
Welcome to the TDengine shell from Linux, Client Version:2.0.5.0
Copyright (c) 2017 by TAOS Data, Inc. All rights reserved.
taos> show databases;
name | created_time | ntables | vgroups | replica | quorum | days | keep1,keep2,keep(D) | cache(MB) | blocks | minrows | maxrows | wallevel | fsync | comp | precision | status |
===================================================================================================================================================================================================================================================================
test | 2020-10-14 10:35:48.617 | 10 | 1 | 1 | 1 | 2 | 3650,3650,3650 | 16 | 6 | 100 | 4096 | 1 | 3000 | 2 | ms | ready |
log | 2020-10-12 09:08:21.651 | 4 | 1 | 1 | 1 | 10 | 30,30,30 | 1 | 3 | 100 | 4096 | 1 | 3000 | 2 | us | ready |
Query OK, 2 row(s) in set (0.045000s)
taos>
```
Go to the C:\TDengine directory under cmd and execute `taos.exe` directly to connect to the TDengine service and enter the TDengine CLI interface, for example, as follows:
```text
C:\TDengine>taos
Welcome to the TDengine shell from Linux, Client Version:2.0.5.0
Copyright (c) 2017 by TAOS Data, Inc. All rights reserved.
taos> show databases;
name | created_time | ntables | vgroups | replica | quorum | days | keep1,keep2,keep(D) | cache(MB) | blocks | minrows | maxrows | wallevel | fsync | comp | precision | status |
===================================================================================================================================================================================================================================================================
test | 2020-10-14 10:35:48.617 | 10 | 1 | 1 | 1 | 2 | 3650,3650,3650 | 16 | 6 | 100 | 4096 | 1 | 3000 | 2 | ms | ready |
log | 2020-10-12 09:08:21.651 | 4 | 1 | 1 | 1 | 10 | 30,30,30 | 1 | 3 | 100 | 4096 | 1 | 3000 | 2 | us | ready |
Query OK, 2 row(s) in set (0.045000s)
taos>
```
import PkgList from "/components/PkgList";
1. 下载客户端安装包
1. Download the client installation package
<PkgList type={1} sys="Windows" />
[所有下载](https://www.taosdata.com/cn/all-downloads/)
[all downloads](https://www.taosdata.com/cn/all-downloads/)
2. 执行安装程序,按提示选择默认值,完成安装
3. 安装路径
2. Execute the installer, select the default value as prompted, and complete the installation
3. Installation path
默认安装路径为:C:\TDengine,其中包括以下文件(目录):
The default installation path is C:\TDengine, including the following files (directories).
- _taos.exe_:TDengine CLI 命令行程序
- _cfg_ : 配置文件目录
- _driver_: 应用驱动动态链接库
- _examples_: 示例程序 bash/C/C#/go/JDBC/Python/Node.js
- _include_: 头文件
- _log_ : 日志文件
- _unins000.exe_: 卸载程序
- _taos.exe_ : TDengine CLI command line program
- _cfg_ : configuration file directory
- _driver_: application driver dynamic link library
- _examples_: sample programs bash/C/C#/go/JDBC/Python/Node.js
- _include_: header files
- _log_ : log file
- _unins000.exe_: uninstaller
4. 配置 taos.cfg
4. configure taos.cfg
编辑 taos.cfg 文件(默认路径 C:\TDengine\cfg\taos.cfg),将 firstEP 修改为 TDengine 服务器的 End Point,例如:`h1.tdengine.com:6030`。
Edit the taos.cfg file (default path C:\TDengine\cfg\taos.cfg) and change the firstEP to the End Point of the TDengine server, for example: `h1.tdengine.com:6030`.
:::tip
1. 如利用 FQDN 连接服务器,必须确认本机网络环境 DNS 已配置好,或在 hosts 文件中添加 FQDN 寻址记录, 如编辑 C:\Windows\system32\drivers\etc\hosts,添加类似如下的记录:`192.168.1.99 h1.taos.com`
2. 卸载:运行 unins000.exe 可卸载 TDengine 应用驱动。
1. If you use FQDN to connect to the server, you must ensure the local network environment DNS is configured, or add FQDN addressing records in the `hosts` file, e.g., edit C:\Windows\system32\drivers\etc\hosts and add a record like the following: `192.168.1.99 h1.tados.com`. 2.
2. Uninstall: Run unins000.exe to uninstall the TDengine application driver.
:::
......@@ -4,39 +4,39 @@ sidebar_label: C/C++
title: C/C++ Connector
---
C/C++ 开发人员可以使用 TDengine 的客户端驱动,即 C/C++连接器 (以下都用 TDengine 客户端驱动表示),开发自己的应用来连接 TDengine 集群完成数据存储、查询以及其他功能。TDengine 客户端驱动的 API 类似于 MySQL 的 C API。应用程序使用时,需要包含 TDengine 头文件 _taos.h_,里面列出了提供的 API 的函数原型;应用程序还要链接到所在平台上对应的动态库。
C/C++ developers can use TDengine's client driver, the C/C++ connector (hereafter referred to as the TDengine client driver), to develop their applications to connect to TDengine clusters for data storing, querying, and other functions. To use it, you need to 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.
```c
#include <taos.h>
```
TDengine 服务端或客户端安装后,`taos.h` 位于:
After TDengine server or client installation, `taos.h` is located at
- Linux`/usr/local/taos/include`
- Windows`C:\TDengine\include`
- Linux: `/usr/local/taos/include`
- Windows: `C:\TDengine\include`
TDengine 客户端驱动的动态库位于:
The dynamic libraries for the TDengine client driver are located in.
- Linux: `/usr/local/taos/driver/libtaos.so`
- Windows: `C:\TDengine\taos.dll`
## 支持的平台
## Supported platforms
请参考[支持的平台列表](/reference/connector#支持的平台)
Please refer to [list of supported platforms](/reference/connector#supported platforms)
## 支持的版本
## Supported versions
TDengine 客户端驱动的版本号与 TDengine 服务端的版本号是一一对应的强对应关系,建议使用与 TDengine 服务端完全相同的客户端驱动。虽然低版本的客户端驱动在前三段版本号一致(即仅第四段版本号不同)的情况下也能够与高版本的服务端相兼容,但这并非推荐用法。强烈不建议使用高版本的客户端驱动访问低版本的服务端。
The version number of the TDengine client driver and the version number of the TDengine server require one-to-one correspondence and recommend using the same client driver as the TDengine server. Although 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), it is not recommended. It is strongly discouraged to use a high version of the client driver to access a low version of the server.
## 安装步骤
## Installation steps
TDengine 客户端驱动的安装请参考 [安装指南](/reference/connector#安装步骤)
Please refer to the [Installation Guide](/reference/connector#installation steps) for TDengine client driver installation
## 建立连接
## Establishing a connection
使用客户端驱动访问 TDengine 集群的基本过程为:建立连接、查询和写入、关闭连接、清除资源。
The basic process of accessing a TDengine cluster using the client driver is to establish a connection, query and write, 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.
```c
TAOS *taos = taos_connect("localhost:6030", "root", "taosdata", NULL, 0);
......@@ -45,29 +45,29 @@ TDengine 客户端驱动的安装请参考 [安装指南](/reference/connector#
exit(1);
}
/* put your code here for read and write */
/* put your code here for query and writing */
taos_close(taos);
taos_cleanup();
```
在上面的示例代码中, `taos_connect` 建立到客户端程序所在主机的 6030 端口的连接,`taos_close`关闭当前连接,`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.
:::note
- 如未特别说明,当 API 的返回值是整数时,_0_ 代表成功,其它是代表失败原因的错误码,当返回值是指针时, _NULL_ 表示失败。
- 所有的错误码以及对应的原因描述在 taoserror.h 文件中。
- If not specified, when the return value of the API is an integer, _0_ means success, the others are error codes representing the reason for failure, and when the return value is a pointer, _NULL_ means failure.
- All error codes and their corresponding causes are described in the taoserror.h file.
:::
## 示例程序
## Example program
本节展示了使用客户端驱动访问 TDengine 集群的常见访问方式的示例代码。
This section shows sample code for standard access methods to TDengine clusters using the client driver.
### 同步查询示例
### Synchronous query example
<details>
<summary>同步查询</summary>
<details
<summary>Synchronous query</summary>
```c
{{#include examples/c/demo.c}}
......@@ -75,10 +75,10 @@ TDengine 客户端驱动的安装请参考 [安装指南](/reference/connector#
</details>
### 异步查询示例
### Asynchronous query example
<details>
<summary>异步查询</summary>
<summary>Asynchronous queries</summary>
```c
{{#include examples/c/asyncdemo.c}}
......@@ -86,10 +86,10 @@ TDengine 客户端驱动的安装请参考 [安装指南](/reference/connector#
</details>
### 参数绑定示例
### Parameter binding example
<details>
<summary>参数绑定</summary>
<summary>Parameter Binding</summary>
```c
{{#include examples/c/prepare.c}}
......@@ -97,10 +97,10 @@ TDengine 客户端驱动的安装请参考 [安装指南](/reference/connector#
</details>
### 无模式写入示例
### Pattern-free writing example
<details>
<summary>无模式写入</summary>
<summary>Mode free write</summary>
```c
{{#include examples/c/schemaless.c}}
......@@ -108,10 +108,10 @@ TDengine 客户端驱动的安装请参考 [安装指南](/reference/connector#
</details>
### 订阅和消费示例
### Subscription and consumption example
<details>
<summary>订阅和消费</summary>
<summary>Subscribe and consume</summary>
```c
{{#include examples/c/subscribe.c}}
......@@ -120,188 +120,190 @@ TDengine 客户端驱动的安装请参考 [安装指南](/reference/connector#
</details>
:::info
更多示例代码及下载请见 [github](https://github.com/taosdata/TDengine/tree/develop/examples/c)
也可以在安装目录下的 examples/c 路径下找到。 该目录下有 makefile,在 Linux 环境下,直接执行 make 就可以编译得到执行文件。
**提示:**在 ARM 环境下编译时,请将 makefile 中的 `-msse4.2` 去掉,这个选项只有在 x64/x86 硬件平台上才能支持。
More example code and downloads are available at [github](https://github.com/taosdata/TDengine/tree/develop/examples/c)
You can find it in the installation directory under the examples/c path. This directory has a makefile and can be compiled under Linux by executing make directly.
**Hint:** When compiling in an ARM environment, please remove `-msse4.2` from the makefile. This option is only supported on x64/x86 hardware platforms.
:::
## API 参考
## API reference
以下分别介绍 TDengine 客户端驱动的基础 API、同步 API、异步 API、订阅 API 和无模式写入 API。
The following describes the basic API, synchronous API, asynchronous API, subscription API, and modeless write API of TDengine client driver, respectively.
### 基础 API
### Basic API
基础 API 用于完成创建数据库连接等工作,为其它 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()`
初始化运行环境。如果应用没有主动调用该 API,那么应用在调用 `taos_connect()` 时将自动调用,故应用程序一般无需手动调用该 API。
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()`
清理运行环境,应用退出前应调用此 API。
Clean up the runtime environment and should be called before the application exits.
- `int taos_options(TSDB_OPTION option, const void * arg, ...)`
- ` int taos_options(TSDB_OPTION option, const void * arg, ...) `
设置客户端选项,目前支持区域设置(`TSDB_OPTION_LOCALE`)、字符集设置(`TSDB_OPTION_CHARSET`)、时区设置(`TSDB_OPTION_TIMEZONE`)、配置文件路径设置(`TSDB_OPTION_CONFIGDIR`)。区域设置、字符集、时区默认为操作系统当前设置。
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:TDengine 管理主节点的 FQDN
- user:用户名
- pass:密码
- db:数据库名字,如果用户没有提供,也可以正常连接,用户可以通过该连接创建新的数据库,如果用户提供了数据库名字,则说明该数据库用户已经创建好,缺省使用该数据库
- port:TDengine 管理主节点的端口号
- host: FQDN of any node in the TDengine cluster
- user: user name
- pass: password
- db: database name, if the user does not provide, it can also be connected correctly, the user can create a new database through this connection, if the user provides the database name, it means that the database user has already created, the default use of the database
- port: the port the tasd program is listening on
返回值为空表示失败。应用程序需要保存返回的参数,以便后续 API 调用。
A null return value indicates a failure. The application needs to save the returned parameters for subsequent use.
:::info
同一进程可以根据不同的 host/port 连接多个 TDengine 集群
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)`
- ` int taos_select_db(TAOS *taos, const char *db)`
将当前的缺省数据库设置为 `db`。
Set the current default database to `db`.
- `void taos_close(TAOS *taos)`
关闭连接,其中`taos`是 `taos_connect()` 函数返回的指针。
Closes the connection, where `taos` is the handle returned by `taos_connect()`.
### 同步查询 API
### Synchronous query APIs
传统的数据库操作 API,都属于同步操作。应用调用 API 后,一直处于阻塞状态,直到服务端返回结果。
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)`
该 API 用来执行 SQL 语句,可以是 DQL、DML 或 DDL 语句。 其中的 `taos` 参数是通过 `taos_connect()` 获得的指针。不能通过返回值是否是 `NULL` 来判断执行结果是否失败,而是需要用 `taos_errno()` 函数解析结果集中的错误代码来进行判断。
Executes an SQL statement, either a DQL, DML, or DDL statement. The `taos` parameter is a handle obtained with `taos_connect()`. You can't tell if the result failed by whether the return value is `NULL`, but by parsing the error code in the result set with the `taos_errno()` function.
- `int taos_result_precision(TAOS_RES *res)`
返回结果集时间戳字段的精度,`0` 代表毫秒,`1` 代表微秒,`2` 代表纳秒。
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)`
- ` 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)` `int taos_field_count(TAOS_RES *res)`
- `int taos_num_fields(TAOS_RES *res)` and `int taos_field_count(TAOS_RES *res)`
这两个 API 等价,用于获取查询结果集中的列数。
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)`
获取被所执行的 SQL 语句影响的行数。
Get the number of rows affected by the executed SQL statement.
- `TAOS_FIELD *taos_fetch_fields(TAOS_RES *res)`
- ` TAOS_FIELD *taos_fetch_fields(TAOS_RES *res)`
获取查询结果集每列数据的属性(列的名称、列的数据类型、列的长度),与 `taos_num_fileds()` 配合使用,可用来解析 `taos_fetch_row()` 返回的一个元组(一行)的数据。 `TAOS_FIELD` 的结构如下:
Gets the properties of each column of the query result set (column name, column data type, column length), used in conjunction with `taos_num_fileds()` to parse a tuple (one row) of data returned by `taos_fetch_row()`. The structure of `TAOS_FIELD` is as follows.
```c
typedef struct taosField {
char name[65]; // column name
uint8_t type; // data type
int16_t bytes; // length, in bytes
char name[65]; // column name
uint8_t type; // data type
int16_t bytes; // length, in bytes
} TAOS_FIELD;
```
- `void taos_stop_query(TAOS_RES *res)`
停止一个查询的执行。
Stops the execution of the current query.
- `void taos_free_result(TAOS_RES *res)`
- ` void taos_free_result(TAOS_RES *res)`
释放查询结果集以及相关的资源。查询完成后,务必调用该 API 释放资源,否则可能导致应用内存泄露。但也需注意,释放资源后,如果再调用 `taos_consume()` 等获取查询结果的函数,将导致应用崩溃。
Frees the query result set and the associated resources. Be sure to call this API to free the resources after the query is completed. Otherwise, it 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)`
获取最近一次 API 调用失败的原因,返回值为字符串。
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)`
- 'int taos_errno(TAOS_RES *res)`
获取最近一次 API 调用失败的原因,返回值为错误代码。
Get the reason for the last API call failure. The return value is the error code.
:::note
2.0 及以上版本 TDengine 推荐数据库应用的每个线程都建立一个独立的连接,或基于线程建立连接池。而不推荐在应用中将该连接 (TAOS\*) 结构体传递到不同的线程共享使用。基于 TAOS 结构体发出的查询、写入等操作具有多线程安全性,但 “USE statement” 等状态量有可能在线程之间相互干扰。此外,C 语言的连接器可以按照需求动态建立面向数据库的新连接(该过程对用户不可见),同时建议只有在程序最后退出的时候才调用 `taos_close()` 关闭连接。
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, etc., issued based on TAOS structures are multi-thread safe, but state quantities such as "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.
:::
### 异步查询 API
### Asynchronous query API
同步 API 之外,TDengine 还提供性能更高的异步调用 API 处理数据插入、查询操作。在软硬件环境相同的情况下,异步 API 处理数据插入的速度比同步 API 快 2 ~ 4 倍。异步 API 采用非阻塞式的调用方式,在系统真正完成某个具体数据库操作前,立即返回。调用的线程可以去处理其他工作,从而可以提升整个应用的性能。异步 API 在网络延迟严重的情况下,优点尤为突出。
TDengine also provides a higher performance asynchronous API to handle data insertion and query operations. 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.
异步 API 都需要应用提供相应的回调函数,回调函数参数设置如下:前两个参数都是一致的,第三个参数依不同的 API 而定。第一个参数 param 是应用调用异步 API 时提供给系统的,用于回调时,应用能够找回具体操作的上下文,依具体实现而定。第二个参数是 SQL 操作的结果集,如果为空,比如 insert 操作,表示没有记录返回,如果不为空,比如 select 操作,表示有记录返回。
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 empty, such as insert operation, it means that there are no records returned, and if it is not empty, such as select operation, it means that there are records returned.
异步 API 对于使用者的要求相对较高,用户可根据具体应用场景选择性使用。下面是两个重要的异步 API:
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);`
异步执行 SQL 语句。
Execute SQL statements asynchronously.
- taos:调用 `taos_connect()` 返回的数据库连接
- sql:需要执行的 SQL 语句
- fp:用户定义的回调函数,其第三个参数 `code` 用于指示操作是否成功,`0` 表示成功,负数表示失败(调用 `taos_errstr()` 可获取失败原因)。应用在定义回调函数的时候,主要处理第二个参数 `TAOS_RES *`,该参数是查询返回的结果集
- param:应用提供一个用于回调的参数
- 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);`
批量获取异步查询的结果集,只能与 `taos_query_a()` 配合使用。其中:
Batch get the result set of an asynchronous query, which can only be used with `taos_query_a()`. The parameters are:
- res:`taos_query_a()` 回调时返回的结果集
- fp:回调函数。其参数 `param` 是用户可定义的传递给回调函数的参数结构体;`numOfRows` 是获取到的数据的行数(不是整个查询结果集的函数)。 在回调函数中,应用可以通过调用 `taos_fetch_row()` 前向迭代获取批量记录中每一行记录。读完一块内的所有记录后,应用需要在回调函数中继续调用 `taos_fetch_rows_a()` 获取下一批记录进行处理,直到返回的记录数 `numOfRows` 为零(结果返回完成)或记录数为负值(查询出错)。
- 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).
TDengine 的异步 API 均采用非阻塞调用模式。应用程序可以用多线程同时打开多张表,并可以同时对每张打开的表进行查询或者插入操作。需要指出的是,**客户端应用必须确保对同一张表的操作完全串行化**,即对同一个表的插入或查询操作未完成时(未返回时),不能够执行第二个插入或查询操作。
TDengine's asynchronous APIs all 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).
### 参数绑定 API
### Parameter Binding API
除了直接调用 `taos_query()` 进行查询,TDengine 也提供了支持参数绑定的 Prepare API,风格与 MySQL 类似,目前也仅支持用问号 `?` 来代表待绑定的参数。
In addition to direct calls to `taos_query()` to perform queries, TDengine also provides a Prepare API that supports parameter binding, similar in style to MySQL, and currently only supports using a question mark `? ` to represent the parameter to be bound.
从 2.1.1.0 和 2.1.2.0 版本开始,TDengine 大幅改进了参数绑定接口对数据写入(INSERT)场景的支持。这样在通过参数绑定接口写入数据时,就避免了 SQL 语法解析的资源消耗,从而在绝大多数情况下显著提升写入性能。此时的典型操作步骤如下:
Starting with versions 2.1.1.0 and 2.1.2.0, TDengine has significantly improved the parameter binding interface's support for 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. 调用 `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()` 释放所有资源。
1. call `taos_stmt_init()` to create the parameter binding object.
2. call `taos_stmt_prepare()` to parse the INSERT statement. 3.
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.
说明:如果 `taos_stmt_execute()` 执行成功,假如不需要改变 SQL 语句的话,那么是可以复用 `taos_stmt_prepare()` 的解析结果,直接进行第 3 ~ 6 步绑定新数据的。但如果执行出错,那么并不建议继续在当前的环境上下文下继续工作,而是建议释放资源,然后从 `taos_stmt_init()` 步骤重新开始。
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 statement. 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.
接口相关的具体函数如下(也可以参考 [prepare.c](https://github.com/taosdata/TDengine/blob/develop/examples/c/prepare.c) 文件中使用对应函数的方式):
The specific functions related to the interface are as follows (see also the [prepare.c](https://github.com/taosdata/TDengine/blob/develop/examples/c/prepare.c) file for the way to use the corresponding functions)
- `TAOS_STMT* taos_stmt_init(TAOS *taos)`
创建一个 TAOS_STMT 对象用于后续调用。
Creates a TAOS_STMT object for subsequent calls.
- `int taos_stmt_prepare(TAOS_STMT *stmt, const char *sql, unsigned long length)`
- ` int taos_stmt_prepare(TAOS_STMT *stmt, const char *sql, unsigned long length)`
解析一条 SQL 语句,将解析结果和参数信息绑定到 stmt 上,如果参数 length 大于 0,将使用此参数作为 SQL 语句的长度,如等于 0,将自动判断 SQL 语句的长度。
Parse a SQL statement, 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 statement. If it is equal to 0, the length of the SQL statement will be determined automatically.
- `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 类似,具体定义如下:
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.
```c
typedef struct TAOS_BIND {
......@@ -317,80 +319,80 @@ TDengine 的异步 API 均采用非阻塞调用模式。应用程序可以用多
- `int taos_stmt_set_tbname(TAOS_STMT* stmt, const char* name)`
(2.1.1.0 版本新增,仅支持用于替换 INSERT 语句中的参数值)
当 SQL 语句中的表名使用了 `?` 占位时,可以使用此函数绑定一个具体的表名。
(New in version 2.1.1.0, only supported for replacing parameter values in INSERT statements)
When the table name in the SQL statement 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)`
(2.1.2.0 版本新增,仅支持用于替换 INSERT 语句中的参数值)
当 SQL 语句中的表名和 TAGS 都使用了 `?` 占位时,可以使用此函数绑定具体的表名和具体的 TAGS 取值。最典型的使用场景是使用了自动建表功能的 INSERT 语句(目前版本不支持指定具体的 TAGS 列)。TAGS 参数中的列数量需要与 SQL 语句中要求的 TAGS 数量完全一致。
(New in version 2.1.2.0, only supported for replacing parameter values in INSERT statements)
When the table name and TAGS in the SQL statement 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 statement.
- `int taos_stmt_bind_param_batch(TAOS_STMT* stmt, TAOS_MULTI_BIND* bind)`
(2.1.1.0 版本新增,仅支持用于替换 INSERT 语句中的参数值)
以多列的方式传递待绑定的数据,需要保证这里传递的数据列的顺序、列的数量与 SQL 语句中的 VALUES 参数完全一致。TAOS_MULTI_BIND 的具体定义如下:
(new in version 2.1.1.0, 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.
```c
typedef struct TAOS_MULTI_BIND {
int buffer_type;
void * buffer;
uintptr_t buffer_length;
uintptr_t * length;
char * is_null;
int num; // the number of columns
int buffer_type;
void * buffer;
uintptr_t buffer_length;
uintptr_t * length;
char * is_null;
int num; // the number of columns
} TAOS_MULTI_BIND;
```
- `int taos_stmt_add_batch(TAOS_STMT *stmt)`
- ` int taos_stmt_add_batch(TAOS_STMT *stmt)`
将当前绑定的参数加入批处理中,调用此函数后,可以再次调用 `taos_stmt_bind_param()` 或 `taos_stmt_bind_param_batch()` 绑定新的参数。需要注意,此函数仅支持 INSERT/IMPORT 语句,如果是 SELECT 等其他 SQL 语句,将返回错误。
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 statements 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)`
- ` TAOS_RES* taos_stmt_use_result(TAOS_STMT *stmt)`
获取语句的结果集。结果集的使用方式与非参数化调用时一致,使用完成后,应对此结果集调用 `taos_free_result()` 以释放资源。
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)`
- ` char * taos_stmt_errstr(TAOS_STMT *stmt)`
(2.1.3.0 版本新增)
用于在其他 STMT API 返回错误(返回错误码或空指针)时获取错误信息。
(new in version 2.1.3.0)
Used to get error information if other STMT APIs return errors (return error codes or null pointers).
### 无模式写入 API
### Write-without-mode API
除了使用 SQL 方式或者使用参数绑定 API 写入数据外,还可以使用 Schemaless 的方式完成写入。Schemaless 可以免于预先创建超级表/数据子表的数据结构,而是可以直接写入数据,TDengine 系统会根据写入的数据内容自动创建和维护所需要的表结构。Schemaless 的使用方式详见 [Schemaless 写入](/reference/schemaless/) 章节,这里介绍与之配套使用的 C/C++ API。
In addition to writing data using the SQL method or the parameter binding API, writing can also be done using Schemaless, 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 is described in the chapter [Schemaless Writing](/reference/schemaless/), 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)`
**功能说明**
该接口将行协议的文本数据写入到 TDengine 中。
**Function description**
This interface writes the text data of the line protocol to TDengine.
**参数说明**
taos: 数据库连接,通过 `taos_connect()` 函数建立的数据库连接。
lines:文本数据。满足解析格式要求的无模式文本字符串。
numLines:文本数据的行数,不能为 0 。
protocol: 行协议类型,用于标识文本数据格式。
precision:文本数据中的时间戳精度字符串。
**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.
**返回值**
TAOS_RES 结构体,应用可以通过使用 `taos_errstr()` 获得错误信息,也可以使用 `taos_errno()` 获得错误码。
在某些情况下,返回的 TAOS_RES 为 `NULL`,此时仍然可以调用 `taos_errno()` 来安全地获得错误码信息。
返回的 TAOS_RES 需要调用方来负责释放,否则会出现内存泄漏。
**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. Otherwise, a memory leak will occur.
**说明**
协议类型是枚举类型,包含以下三种格式:
**Description**
The protocol type is enumerated and contains the following three formats.
- TSDB_SML_LINE_PROTOCOL:InfluxDB 行协议(Line Protocol)
- TSDB_SML_TELNET_PROTOCOL: OpenTSDB Telnet 文本行协议
- TSDB_SML_JSON_PROTOCOL: OpenTSDB Json 协议格式
- 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
时间戳分辨率的定义,定义在 taos.h 文件中,具体内容如下:
The timestamp resolution definitions are in the taos.h file, as follows
- TSDB_SML_TIMESTAMP_NOT_CONFIGURED = 0,
- TSDB_SML_TIMESTAMP_HOURS,
......@@ -400,51 +402,51 @@ TDengine 的异步 API 均采用非阻塞调用模式。应用程序可以用多
- TSDB_SML_TIMESTAMP_MICRO_SECONDS,
- TSDB_SML_TIMESTAMP_NANO_SECONDS
需要注意的是,时间戳分辨率参数只在协议类型为 `SML_LINE_PROTOCOL` 的时候生效。
对于 OpenTSDB 的文本协议,时间戳的解析遵循其官方解析规则 — 按照时间戳包含的字符的数量来确认时间精度。
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.
**支持版本**
该功能接口从 2.3.0.0 版本开始支持。
**Supported Versions**
This feature interface is supported from version 2.3.0.0.
### 订阅和消费 API
### Subscription and Consumption API
订阅 API 目前支持订阅一张或多张表,并通过定期轮询的方式不断获取写入表中的最新数据。
The Subscription API currently supports subscribing to one or more tables and continuously fetching the latest data written to them by polling periodically.
- `TAOS_SUB *taos_subscribe(TAOS* taos, int restart, const char* topic, const char *sql, TAOS_SUBSCRIBE_CALLBACK fp, void *param, int interval)`
该函数负责启动订阅服务,成功时返回订阅对象,失败时返回 `NULL`,其参数为:
This function is responsible for starting the subscription service, returning the subscription object on success and `NULL` on failure, with the following parameters.
- taos:已经建立好的数据库连接
- restart:如果订阅已经存在,是重新开始,还是继续之前的订阅
- topic:订阅的主题(即名称),此参数是订阅的唯一标识
- sql:订阅的查询语句,此语句只能是 `select` 语句,只应查询原始数据,只能按时间正序查询数据
- fp:收到查询结果时的回调函数(稍后介绍函数原型),只在异步调用时使用,同步调用时此参数应该传 `NULL`
- param:调用回调函数时的附加参数,系统 API 将其原样传递到回调函数,不进行任何处理
- interval:轮询周期,单位为毫秒。异步调用时,将根据此参数周期性的调用回调函数,为避免对系统性能造成影响,不建议将此参数设置的过小;同步调用时,如两次调用 `taos_consume()` 的间隔小于此周期,API 将会阻塞,直到时间间隔超过此周期。
- taos: the database connection that has been established
- restart: if the subscription already exists, whether to restart or continue the previous subscription
- topic: the topic of the subscription (i.e., the name). This parameter is the unique identifier of the subscription
- sql: the query statement of the subscription, this statement can only be `select` statement, only the original data should be queried, only the data can be queried in time order
- fp: the callback function when the query result is received (the function prototype will be introduced later), only used when called asynchronously. This parameter should be passed `NULL` when called synchronously
- param: additional parameter when calling the callback function, the system API will pass it to the callback function as it is, without any processing
- interval: polling period in milliseconds. The callback function will be called periodically according to this parameter when called asynchronously. not recommended to set this parameter too small To avoid impact on system performance when called synchronously. If the interval between two calls to `taos_consume()` is less than this period, the API will block until the interval exceeds this period.
- `typedef void (*TAOS_SUBSCRIBE_CALLBACK)(TAOS_SUB* tsub, TAOS_RES *res, void* param, int code)`
- ` typedef void (*TAOS_SUBSCRIBE_CALLBACK)(TAOS_SUB* tsub, TAOS_RES *res, void* param, int code)`
异步模式下,回调函数的原型,其参数为:
The prototype of the callback function in asynchronous mode with the following parameters
- tsub:订阅对象
- res:查询结果集,注意结果集中可能没有记录
- param:调用 `taos_subscribe()` 时客户程序提供的附加参数
- code:错误码
- tsub: subscription object
- res: query result set, note that there may be no records in the result set
- param: additional parameters provided by the client program when calling `taos_subscribe()`
- code: error code
:::note
在这个回调函数里不可以做耗时过长的处理,尤其是对于返回的结果集中数据较多的情况,否则有可能导致客户端阻塞等异常状态。如果必须进行复杂计算,则建议在另外的线程中进行处理。
The callback function should not take too long to process, especially if the returned result set has a lot of data. Otherwise, it may lead to an abnormal state, such as client blocking. If you must perform complex calculations, we recommend handling them in a separate thread.
:::
- `TAOS_RES *taos_consume(TAOS_SUB *tsub)`
同步模式下,该函数用来获取订阅的结果。 用户应用程序将其置于一个循环之中。 如两次调用 `taos_consume()` 的间隔小于订阅的轮询周期,API 将会阻塞,直到时间间隔超过此周期。如果数据库有新记录到达,该 API 将返回该最新的记录,否则返回一个没有记录的空结果集。 如果返回值为 `NULL`,说明系统出错。 异步模式下,用户程序不应调用此 API。
In synchronous mode, this function is used to fetch the results of a subscription. The user application places it in a loop. If the interval between two calls to `taos_consume()` is less than the polling period of the subscription, the API will block until the interval exceeds this period. If a new record arrives in the database, the API returns that latest record. Otherwise, it returns an empty result set with no records. If the return value is `NULL`, there is a system error. This API should not be called by user programs in asynchronous mode.
:::note
在调用 `taos_consume()` 之后,用户应用应确保尽快调用 `taos_fetch_row()` 或 `taos_fetch_block()` 来处理订阅结果,否则服务端会持续缓存查询结果数据等待客户端读取,极端情况下会导致服务端内存消耗殆尽,影响服务稳定性。
After calling `taos_consume()`, the user application should make sure to call `taos_fetch_row()` or `taos_fetch_block()` to process the subscription results as soon as possible. Otherwise, the server-side will keep caching the query result data waiting to be read by the client, which in extreme cases will cause the server side to run out of memory and affect the stability of the service.
:::
- `void taos_unsubscribe(TAOS_SUB *tsub, int keepProgress)`
取消订阅。 如参数 `keepProgress` 不为 0,API 会保留订阅的进度信息,后续调用 `taos_subscribe()` 时可以基于此进度继续;否则将删除进度信息,后续只能重新开始读取数据。
Unsubscribe. If the parameter `keepProgress` is not 0, the API will keep the progress information of the subscription, and subsequent calls to `taos_subscribe()` will continue based on this progress; otherwise, the progress information will be deleted, and subsequent readings will have to be restarted.
......@@ -16,54 +16,55 @@ import CSOpenTSDBJson from "../../04-develop/03-insert-data/_cs_opts_json.mdx"
import CSQuery from "../../04-develop/04-query-data/_cs.mdx"
import CSAsyncQuery from "../../04-develop/04-query-data/_cs_async.mdx"
`TDengine.Connector` 是 TDengine 提供的 C# 语言连接器。C# 开发人员可以通过它开发存取 TDengine 集群数据的 C# 应用软件。
`TDengine.Connector` 连接器支持通过 TDengine 客户端驱动(taosc)建立与 TDengine 运行实例的连接,提供数据写入、查询、订阅、schemaless 数据写入、参数绑定接口数据写入等功能 `TDengine.Connector` 目前暂未提供 REST 连接方式,用户可以参考 [RESTful APIs](https://docs.taosdata.com//reference/restful-api/) 文档自行编写。
TDengine.Connector` is a C# language connector provided by TDengine that allows C# developers to develop C# applications that access TDengine cluster data.
本文介绍如何在 Linux 或 Windows 环境中安装 `TDengine.Connector`,并通过 `TDengine.Connector` 连接 TDengine 集群,进行数据写入、查询等基本操作。
The `TDengine.Connector` connector supports connection to TDengine runtime instances via the TDengine client driver (taosc), providing data writing, querying, subscription, schemaless data writing, bind interface data writing, etc. The `TDengine.Connector` currently does not provide a REST connection. REST connection is not yet available. Users can write their RESTful APIs by referring to the [RESTful APIs](https://docs.taosdata.com//reference/restful-api/) documentation.
`TDengine.Connector` 的源码托管在 [GitHub](https://github.com/taosdata/taos-connector-dotnet)。
This article describes how to install `TDengine.Connector` in a Linux or Windows environment and connect to TDengine clusters via `TDengine.Connector` to perform basic operations such as data writing and querying.
## 支持的平台
The source code of `TDengine.Connector` is hosted on [GitHub](https://github.com/taosdata/taos-connector-dotnet).
支持的平台和 TDengine 客户端驱动支持的平台一致。
## Supported Platforms
## 版本支持
The supported platforms are the same as those supported by the TDengine client driver.
请参考[版本支持列表](/reference/connector#版本支持)
## Version support
## 支持的功能特性
Please refer to [version support list](/reference/connector#version support)
1. 连接管理
2. 普通查询
3. 连续查询
4. 参数绑定
5. 订阅功能
## Supported features
1. connection management
2. general query
3. continuous query
4. parameter binding
5. subscription function
6. Schemaless
## 安装步骤
## Installation Steps
### 安装前准备
### Pre-installation preparation
* 安装 [.NET SDK](https://dotnet.microsoft.com/download)
* [Nuget 客户端](https://docs.microsoft.com/en-us/nuget/install-nuget-client-tools) (可选安装)
* 安装 TDengine 客户端驱动,具体步骤请参考[安装客户端驱动](/reference/connector#安装客户端驱动)
* Install the [.NET SDK](https://dotnet.microsoft.com/download)
* [Nuget Client](https://docs.microsoft.com/en-us/nuget/install-nuget-client-tools) (optional installation)
* Install TDengine client driver, please refer to [Install client driver](/reference/connector#Install client driver) for details
### 使用 dotnet CLI 安装
### Install using dotnet CLI
<Tabs defaultValue="CLI">
<TabItem value="CLI" label="使用 dotnet CLI 获取 C# 驱动">
<TabItem value="CLI" label="Get C# driver using dotnet CLI">
可以在当前 .NET 项目的路径下,通过 dotnet 命令引用 Nuget 中发布的 `TDengine.Connector` 到当前项目。
You can reference the `TDengine.Connector` published in Nuget to the current project via the `dotnet` command under the path of the existing .NET project.
``` bash
dotnet add package TDengine.Connector
```
</TabItem>
<TabItem value="source" label="使用源码获取 C# 驱动">
</TabItem
<TabItem value="source" label="Use source code to get C# driver">
可以下载 TDengine 的源码,直接引用最新版本的 TDengine.Connector 库
You can download TDengine's source code and directly reference the latest version of the TDengine.Connector library
```bash
git clone https://github.com/taosdata/TDengine.git
......@@ -76,7 +77,7 @@ dotnet add TDengineDriver/TDengineDriver.csproj
</TabItem>
</Tabs>
## 建立连接
## Create a connection
``` C#
using TDengineDriver;
......@@ -111,79 +112,79 @@ namespace TDengineExample
```
## 使用示例
## Usage examples
### 写入数据
### Write data
#### SQL 写入
#### SQL Write
<CSInsert />
#### InfluxDB 行协议写入
#### InfluxDB line protocol write
<CSInfluxLine />
#### OpenTSDB Telnet 行协议写入
#### OpenTSDB Telnet line protocol write
<CSOpenTSDBTelnet />
#### OpenTSDB JSON 行协议写入
#### OpenTSDB JSON line protocol write
<CSOpenTSDBJson />
### 查询数据
### Query data
#### 同步查询
#### Synchronous Query
<CSQuery />
#### 异步查询
#### Asynchronous query
<CSAsyncQuery />
### 更多示例程序
### More sample programs
|示例程序 | 示例程序描述 |
|--------------------------------------------------------------------------------------------------------------------|--------------------------------------------|
| [C#checker](https://github.com/taosdata/TDengine/tree/develop/examples/C%23/C%23checker) | 使用 TDengine.Connector 可以通过 help 命令中提供的参数,测试C# Driver的同步写入和查询 |
| [TDengineTest](https://github.com/taosdata/TDengine/tree/develop/examples/C%23/TDengineTest) | 使用 TDengine.Connector 实现的简单写入和查询的示例 |
| [insertCn](https://github.com/taosdata/TDengine/tree/develop/examples/C%23/insertCn) | 使用 TDengine.Connector 实现的写入和查询中文字符的示例 |
| [jsonTag](https://github.com/taosdata/TDengine/tree/develop/examples/C%23/jsonTag) | 使用 TDengine.Connector 实现的写入和查询 json tag 类型数据的示例 |
| [stmt](https://github.com/taosdata/TDengine/tree/develop/examples/C%23/stmt) | 使用 TDengine.Connector 实现的参数绑定的示例 |
| [schemaless](https://github.com/taosdata/TDengine/tree/develop/examples/C%23/schemaless) | 使用 TDengine.Connector 实现的使用 schemaless 写入的示例 |
| [benchmark](https://github.com/taosdata/TDengine/tree/develop/examples/C%23/taosdemo) | 使用 TDengine.Connector 实现的简易 Benchmark |
| [async query](https://github.com/taosdata/taos-connector-dotnet/blob/develop/examples/QueryAsyncSample.cs) | 使用 TDengine.Connector 实现的异步查询的示例 |
| [subscribe](https://github.com/taosdata/taos-connector-dotnet/blob/develop/examples/SubscribeSample.cs) | 使用 TDengine.Connector 实现的订阅数据的示例 |
|Sample program |Sample program description |
|--------------------------------------------------------------------------------------------------------------------|------------ --------------------------------|
| [C#checker](https://github.com/taosdata/TDengine/tree/develop/examples/C%23/C%23checker) | Using TDengine.Connector, you can test C# Driver's synchronous writes and queries |
| [TDengineTest](https://github.com/taosdata/TDengine/tree/develop/examples/C%23/TDengineTest) | A simple example of writing and querying using TDengine.
| [insertCn](https://github.com/taosdata/TDengine/tree/develop/examples/C%23/insertCn) | Example of writing and querying Chinese characters using TDengine.
| [jsonTag](https://github.com/taosdata/TDengine/tree/develop/examples/C%23/jsonTag) | Example of writing and querying JSON tag type data using TDengine.
| [stmt](https://github.com/taosdata/TDengine/tree/develop/examples/C%23/stmt) | Example of parameter binding using TDengine.
| [schemaless](https://github.com/taosdata/TDengine/tree/develop/examples/C%23/schemaless) | Example of writing with schemaless implemented using TDengine. |schemaless
| [benchmark](https://github.com/taosdata/TDengine/tree/develop/examples/C%23/taosdemo) | A simple benchmark implemented using TDengine.
| [async query](https://github.com/taosdata/taos-connector-dotnet/blob/develop/examples/QueryAsyncSample.cs) | Example of an asynchronous query implemented using TDengine. Example of an asynchronous query
| [subscribe](https://github.com/taosdata/taos-connector-dotnet/blob/develop/examples/SubscribeSample.cs) | Example of subscribing to data using TDengine. Data example
## 重要更新记录
## Important update records
| TDengine.Connector | 说明 |
| TDengine.Connector | Description |
|--------------------|--------------------------------|
| 1.0.6 | 修复 schemaless 在 1.0.4 和 1.0.5 中失效 bug。 |
| 1.0.5 | 修复 Windows 同步查询中文报错 bug。 |
| 1.0.4 | 新增异步查询,订阅等功能。修复绑定参数 bug。 |
| 1.0.3 | 新增参数绑定、schemaless、 json tag等功能。 |
| 1.0.2 | 新增连接管理、同步查询、错误信息等功能。 |
| 1.0.6 | Fix schemaless bug in 1.0.4 and 1.0.5. |
| 1.0.5 | Fix Windows sync query Chinese error bug. | 1.0.4 | Fix schemaless bug.
| 1.0.4 | Add asynchronous query, subscription, and other functions. Fix the binding parameter bug.
| 1.0.3 | Add parameter binding, schemaless, JSON tag, etc. | new
| 1.0.2 | Add connection management, synchronous query, error messages, etc. ## Other
## 其他说明
## Other descriptions
### 第三方驱动
### Third-party driver
`Maikebing.Data.Taos` 是一个 TDengine 的 ADO.NET 连接器,支持 Linux,Windows 平台。该连接器由社区贡献者`麦壳饼@@maikebing` 提供,具体请参考:
`Taos` is an ADO.NET connector for TDengine, supporting Linux and Windows platforms. Community contributor `Maikebing@@maikebing contributes the connector`. Please refer to:
* 接口下载:<https://github.com/maikebing/Maikebing.EntityFrameworkCore.Taos>
* 用法说明:<https://www.taosdata.com/blog/2020/11/02/1901.html>
* Interface download:<https://github.com/maikebing/Maikebing.EntityFrameworkCore.Taos>
* Usage notes:<https://www.taosdata.com/blog/2020/11/02/1901.html>
## 常见问题
## Frequently Asked Questions
1. "Unable to establish connection""Unable to resolve FQDN"
1. "Unable to establish connection", "Unable to resolve FQDN"
一般是因为 FQDN 配置不正确。可以参考[如何彻底搞懂 TDengine 的 FQDN](https://www.taosdata.com/blog/2021/07/29/2741.html)解决。
Usually, because the FQDN configuration is incorrect, you can refer to [How to understand TDengine's FQDN thoroughly](https://www.taosdata.com/blog/2021/07/29/2741.html) to solve it. 2.
2. Unhandled exception. System.DllNotFoundException: Unable to load DLL 'taos' or one of its dependencies: 找不到指定的模块。
Unhandled exception. System.DllNotFoundException: Unable to load DLL 'taos' or one of its dependencies: The specified module cannot be found.
一般是因为程序没有找到依赖的客户端驱动。解决方法为:Windows 下可以将 `C:\TDengine\driver\taos.dll` 拷贝到 `C:\Windows\System32\ ` 目录下,Linux 下建立如下软链接 `ln -s /usr/local/taos/driver/libtaos.so.x.x.x.x /usr/lib/libtaos.so` 即可。
This is usually because the program did not find the dependent client driver. The solution is to copy `C:\TDengine\driver\taos.dll` to the `C:\Windows\System32\` directory on Windows, and create the following softlink on Linux `ln -s /usr/local/taos/driver/libtaos.so.x.x .x.x /usr/lib/libtaos.so` will work.
## API 参考
## API Reference
[API 参考](https://docs.taosdata.com/api/connector-csharp/html/860d2ac1-dd52-39c9-e460-0829c4e5a40b.htm)
[API Reference](https://docs.taosdata.com/api/connector-csharp/html/860d2ac1-dd52-39c9-e460-0829c4e5a40b.htm)
......@@ -15,67 +15,67 @@ import GoOpenTSDBTelnet from "../../04-develop/03-insert-data/_go_opts_telnet.md
import GoOpenTSDBJson from "../../04-develop/03-insert-data/_go_opts_json.mdx"
import GoQuery from "../../04-develop/04-query-data/_go.mdx"
`driver-go` TDengine 的官方 Go 语言连接器,实现了 Go 语言[ database/sql ](https://golang.org/pkg/database/sql/) 包的接口。Go 开发人员可以通过它开发存取 TDengine 集群数据的应用软件。
`driver-go` is the official Go language connector for TDengine, which implements the interface to the Go language [ database/sql ](https://golang.org/pkg/database/sql/) package. Go developers can use it to develop applications that access TDengine cluster data.
`driver-go` 提供两种建立连接的方式。一种是**原生连接**,它通过 TDengine 客户端驱动程序(taosc)原生连接 TDengine 运行实例,支持数据写入、查询、订阅、schemaless 接口和参数绑定接口等功能。另外一种是 **REST 连接**,它通过 taosAdapter 提供的 REST 接口连接 TDengine 运行实例。REST 连接实现的功能特性集合和原生连接有少量不同。
`driver-go` provides two ways to establish connections. One is **native connection**, which connects to TDengine runtime instances natively through the TDengine client driver (taosc), supporting data writing, querying, subscriptions, schemaless interface, and parameter binding interface. The other is the **REST connection**, which connects to TDengine runtime instances via the REST interface provided by taosAdapter. The set of features implemented by the REST connection differs slightly from the native connection.
本文介绍如何安装 `driver-go`,并通过 `driver-go` 连接 TDengine 集群、进行数据查询、数据写入等基本操作。
This article describes how to install `driver-go` and connect to TDengine clusters and perform basic operations such as data query and data writing through `driver-go`.
`driver-go` 的源码托管在 [GitHub](https://github.com/taosdata/driver-go)
The source code of `driver-go` is hosted on [GitHub](https://github.com/taosdata/driver-go).
## 支持的平台
## Supported Platforms
原生连接支持的平台和 TDengine 客户端驱动支持的平台一致。
REST 连接支持所有能运行 Go 的平台。
Native connections are supported on the same platforms as the TDengine client driver.
REST connections are supported on all platforms that can run Go.
## 版本支持
## Version support
请参考[版本支持列表](/reference/connector#版本支持)
Please refer to [version support list](/reference/connector#version support)
## 支持的功能特性
## Supported features
### 原生连接
### Native connections
“原生连接”指连接器通过 TDengine 客户端驱动(taosc)直接与 TDengine 运行实例建立的连接。支持的功能特性有:
A "native connection" is established by the connector directly to the TDengine runtime instance via the TDengine client driver (taosc). The supported functional features are
* 普通查询
* 连续查询
* 订阅
* schemaless 接口
* 参数绑定接口
* Normal queries
* Continuous queries
* Subscriptions
* schemaless interface
* parameter binding interface
### REST 连接
### REST connection
"REST 连接"指连接器通过 taosAdapter 组件提供的 REST API TDengine 运行实例建立的连接。支持的功能特性有:
A "REST connection" is a connection between a connector and a TDengine runtime instance via the REST API provided by the taosAdapter component. The following features are supported.
* 普通查询
* 连续查询
* General queries
* Continuous queries
## 安装步骤
## Installation steps
### 安装前准备
### Pre-installation
* 安装 Go 开发环境(Go 1.14 及以上,GCC 4.8.5 及以上)
* 如果使用原生连接器,请安装 TDengine 客户端驱动,具体步骤请参考[安装客户端驱动](/reference/connector#安装客户端驱动)
* Install Go development environment (Go 1.14 and above, GCC 4.8.5 and above)
* If you use the native connector, please install the TDengine client driver. Please refer to [Install Client Driver](/reference/connector#Install Client Driver) for specific steps
配置好环境变量,检查命令:
Configure the environment variables and check the command.
* ```go env```
* ```gcc -v```
* ```go env``
* ```gcc -v``
### 使用 go get 安装
### Use go get to install
`go get -u github.com/taosdata/driver-go/v2@develop`
``go get -u github.com/taosdata/driver-go/v2@develop``
### 使用 go mod 管理
### Manage with go mod
1. 使用 `go mod` 命令初始化项目:
1. Initialize the project with the `go mod` command.
```text
``text
go mod init taos-demo
```
``` text
2. 引入 taosSql
2. Introduce taosSql: ``text
```go
import (
......@@ -84,46 +84,46 @@ REST 连接支持所有能运行 Go 的平台。
)
```
3. 使用 `go mod tidy` 更新依赖包:
3. Update the dependency packages with `go mod tidy`.
```text
go mod tidy
```
``` 4.
4. 使用 `go run taos-demo` 运行程序或使用 `go build` 命令编译出二进制文件。
4. Run the program with `go run taos-demo` or compile the binary with the `go build` command.
```text
go run taos-demo
go build
```
## 建立连接
## Create a connection
### 数据源名称(DSN
### Data source name (DSN)
数据源名称具有通用格式,例如 [PEAR DB](http://pear.php.net/manual/en/package.database.db.intro-dsn.php),但没有类型前缀(方括号表示可选):
Data source names have a standard format, e.g. [PEAR DB](http://pear.php.net/manual/en/package.database.db.intro-dsn.php), but no type prefix (square brackets indicate optionally): the
``` text
[username[:password]@][protocol[(address)]]/[dbname][?param1=value1&...&paramN=valueN]
[username[:password]@][protocol[(address)]]/[dbname][?param1=value1&... &paramN=valueN]
```
完整形式的 DSN
DSN in full form.
```text
username:password@protocol(address)/dbname?param=value
```
### 使用连接器进行连接
### Connecting using connectors
<Tabs defaultValue="native">
<TabItem value="native" label="原生连接">
<TabItem value="native" label="native connection">
_taosSql_ 通过 cgo 实现了 Go `database/sql/driver` 接口。只需要引入驱动就可以使用 [`database/sql`](https://golang.org/pkg/database/sql/) 的接口。
_taosSql_ implements Go's `database/sql/driver` interface via cgo. You can use the [`database/sql`](https://golang.org/pkg/database/sql/) interface by simply introducing the driver.
使用 `taosSql` 作为 `driverName` 并且使用一个正确的 [DSN](#DSN) 作为 `dataSourceName`DSN 支持的参数:
Use `taosSql` as `driverName` and use a correct [DSN](#DSN) as `dataSourceName`, DSN supports the following parameters.
* configPath 指定 taos.cfg 目录
* configPath specifies the taos.cfg directory
示例:
Example.
```go
package main
......@@ -136,26 +136,26 @@ import (
)
func main() {
var taosUri = "root:taosdata/tcp(localhost:6030)/"
var taosUri = "root:taosdata@tcp(localhost:6030)/"
taos, err := sql.Open("taosSql", taosUri)
if err != nil {
if err ! = nil {
fmt.Println("failed to connect TDengine, err:", err)
return
}
}
```
</TabItem>
<TabItem value="rest" label="REST 连接">
</TabItem
<TabItem value="rest" label="REST connection">
_taosRestful_ 通过 `http client` 实现了 Go `database/sql/driver` 接口。只需要引入驱动就可以使用[`database/sql`](https://golang.org/pkg/database/sql/)的接口。
_taosRestful_ implements Go's `database/sql/driver` interface via `http client`. You can use the [`database/sql`](https://golang.org/pkg/database/sql/) interface by simply introducing the driver.
使用 `taosRestful` 作为 `driverName` 并且使用一个正确的 [DSN](#DSN) 作为 `dataSourceName`DSN 支持的参数:
Use `taosRestful` as `driverName` and use a correct [DSN](#DSN) as `dataSourceName` with the following parameters supported by the DSN.
* `disableCompression` 是否接受压缩数据,默认为 true 不接受压缩数据,如果传输数据使用 gzip 压缩设置为 false
* `readBufferSize` 读取数据的缓存区大小默认为 4K4096),当查询结果数据量多时可以适当调大该值。
* `disableCompression` whether to accept compressed data, default is true do not accept compressed data, set to false if transferring data using gzip compression.
* `readBufferSize` The default size of the buffer for reading data is 4K (4096), which can be adjusted upwards when the query result has a lot of data.
示例:
Example.
```go
package main
......@@ -168,9 +168,9 @@ import (
)
func main() {
var taosUri = "root:taosdata/http(localhost:6041)/"
var taosUri = "root:taosdata@http(localhost:6041)/"
taos, err := sql.Open("taosRestful", taosUri)
if err != nil {
if err ! = nil {
fmt.Println("failed to connect TDengine, err:", err)
return
}
......@@ -179,42 +179,42 @@ func main() {
</TabItem>
</Tabs>
## 使用示例
## Usage examples
### 写入数据
### Write data
#### SQL 写入
#### SQL Write
<GoInsert />
#### InfluxDB 行协议写入
#### InfluxDB line protocol write
<GoInfluxLine />
#### OpenTSDB Telnet 行协议写入
#### OpenTSDB Telnet line protocol write
<GoOpenTSDBTelnet />
#### OpenTSDB JSON 行协议写入
#### OpenTSDB JSON line protocol write
<GoOpenTSDBJson />
### 查询数据
### Query data
<GoQuery />
### 更多示例程序
### More sample programs
* [示例程序](https://github.com/taosdata/TDengine/tree/develop/examples/go)
* [视频教程](https://www.taosdata.com/blog/2020/11/11/1951.html)
* [sample program](https://github.com/taosdata/TDengine/tree/develop/examples/go)
* [Video tutorial](https://www.taosdata.com/blog/2020/11/11/1951.html).
## 使用限制
## Usage limitations
由于 REST 接口无状态所以 `use db` 语法不会生效,需要将 db 名称放到 SQL 语句中,如:`create table if not exists tb1 (ts timestamp, a int)`改为`create table if not exists test.tb1 (ts timestamp, a int)`否则将报错`[0x217] Database not specified or available`
Since the REST interface is stateless, the `use db` syntax will not work. You need to put the db name into the SQL statement, e.g. `create table if not exists tb1 (ts timestamp, a int)` to `create table if not exists test.tb1 (ts timestamp, a int)` otherwise it will report the error `[0x217] Database not specified or available`.
也可以将 db 名称放到 DSN 中,将 `root:taosdata@http(localhost:6041)/` 改为 `root:taosdata@http(localhost:6041)/test`,此方法在 TDengine 2.4.0.5 版本的 taosAdapter 开始支持。当指定的 db 不存在时执行 `create database` 语句不会报错,而执行针对该 db 的其他查询或写入操作会报错。
You can also put the db name in the DSN by changing `root:taosdata@http(localhost:6041)/` to `root:taosdata@http(localhost:6041)/test`. This method is supported by taosAdapter in TDengine 2.4.0.5. is supported since TDengine 2.4.0.5. Executing the `create database` statement when the specified db does not exist will not report an error while executing other queries or writing against that db will report an error.
完整示例如下:
The complete example is as follows.
```go
package main
......@@ -264,148 +264,148 @@ func main() {
}
```
## 常见问题
## Frequently Asked Questions
1. 无法找到包 `github.com/taosdata/driver-go/v2/taosRestful`
1. Cannot find the package `github.com/taosdata/driver-go/v2/taosRestful`
`go.mod` require 块对`github.com/taosdata/driver-go/v2`的引用改为`github.com/taosdata/driver-go/v2 develop`,之后执行 `go mod tidy`
Change the reference to `github.com/taosdata/driver-go/v2` in the require block in `go.mod` to `github.com/taosdata/driver-go/v2 develop`, then execute `go mod tidy`.
2. database/sql stmt(参数绑定)相关接口崩溃
2. stmt (parameter binding) related interface in database/sql crashes
REST 不支持参数绑定相关接口,建议使用`db.Exec``db.Query`
REST does not support parameter binding related interface. It is recommended to use `db.Exec` and `db.Query`.
3. 使用 `use db` 语句后执行其他语句报错 `[0x217] Database not specified or available`
3. error `[0x217] Database not specified or available` after executing other statements with `use db` statement
REST 接口中 SQL 语句的执行无上下文关联,使用 `use db` 语句不会生效,解决办法见上方使用限制章节。
The execution of SQL statements in the REST interface is not contextual, so using `use db` statement will not work, see the usage restrictions section above.
4. 使用 taosSql 不报错使用 taosRestful 报错 `[0x217] Database not specified or available`
4. use taosSql without error use taosRestful with error `[0x217] Database not specified or available`
因为 REST 接口无状态,使用 `use db` 语句不会生效,解决办法见上方使用限制章节。
Because the REST interface is stateless, using the `use db` statement will not take effect. See the usage restrictions section above.
5. 升级 `github.com/taosdata/driver-go/v2/taosRestful`
5. Upgrade `github.com/taosdata/driver-go/v2/taosRestful`
`go.mod` 文件中对 `github.com/taosdata/driver-go/v2` 的引用改为 `github.com/taosdata/driver-go/v2 develop`,之后执行 `go mod tidy`
Change the reference to `github.com/taosdata/driver-go/v2` in the `go.mod` file to `github.com/taosdata/driver-go/v2 develop`, then execute `go mod tidy`.
6. `readBufferSize` 参数调大后无明显效果
6. `readBufferSize` parameter has no significant effect after being increased
`readBufferSize` 调大后会减少获取结果时 `syscall` 的调用。如果查询结果的数据量不大,修改该参数不会带来明显提升,如果该参数修改过大,瓶颈会在解析 JSON 数据。如果需要优化查询速度,需要根据实际情况调整该值来达到查询效果最优。
If you increase `readBufferSize` will reduce the number of `syscall` calls when fetching results. If the query result is more petite, modifying this parameter will not improve significantly. If you increase the parameter too much, the bottleneck will be parsing JSON data. If you need to optimize the query speed, you must adjust the value according to the actual situation to achieve the best query result.
7. `disableCompression` 参数设置为 `false` 时查询效率降低
7. `disableCompression` parameter is set to `false` when the query efficiency is reduced
`disableCompression` 参数设置为 `false` 时查询结果会使用 `gzip` 压缩后传输,拿到数据后要先进行 `gzip` 解压。
When set `disableCompression` parameter to `false`, the query result will be compressed by `gzip` and then transmitted, so you have to decompress the data by `gzip` after getting it.
8. `go get` 命令无法获取包,或者获取包超时
8. `go get` command can't get the package, or timeout to get the package
设置 Go 代理 `go env -w GOPROXY=https://goproxy.cn,direct`
Set Go proxy `go env -w GOPROXY=https://goproxy.cn,direct`.
## 常用 API
## Common APIs
### database/sql API
* `sql.Open(DRIVER_NAME string, dataSourceName string) *DB`
API 用来打开 DB,返回一个类型为 \*DB 的对象。
Use This API to open a DB, returning an object of type \*DB.
:::info
API 成功创建的时候,并没有做权限等检查,只有在真正执行 Query 或者 Exec 的时候才能真正的去创建连接,并同时检查 user/password/host/port 是不是合法。
This API is created successfully without checking permissions, but only when you execute a Query or Exec, and check if user/password/host/port is legal.
:::
* `func (db *DB) Exec(query string, args ...interface{}) (Result, error)`
* `func (db *DB) Exec(query string, args . .interface{}) (Result, error)`
`sql.Open` 内置的方法,用来执行非查询相关 SQL
`sql.Open` built-in method to execute non-query related SQL.
* `func (db *DB) Query(query string, args ...interface{}) (*Rows, error)`
* `func (db *DB) Query(query string, args ... . interface{}) (*Rows, error)`
`sql.Open` 内置的方法,用来执行查询语句。
`sql.Open` Built-in method to execute query statements.
### 高级功能(afAPI
### Advanced functions (af) API
`af` 包封装了连接管理、订阅、schemaless、参数绑定等 TDengine 高级功能。
The `af` package encapsulates TDengine advanced functions such as connection management, subscriptions, schemaless, parameter binding, etc.
#### 连接管理
#### Connection management
* `af.Open(host, user, pass, db string, port int) (*Connector, error)`
API 通过 cgo 创建与 taosd 的连接。
This API creates a connection to taosd via cgo.
* `func (conn *Connector) Close() error`
关闭与 taosd 的连接。
Closes the connection.
#### 订阅
#### Subscribe to
* `func (conn *Connector) Subscribe(restart bool, topic string, sql string, interval time.Duration) (Subscriber, error)`
订阅数据。
Subscribe to data.
* `func (s *taosSubscriber) Consume() (driver.Rows, error)`
消费订阅数据,返回 `database/sql/driver` 包的 `Rows` 结构。
Consume the subscription data, returning the `Rows` structure of the `database/sql/driver` package.
* `func (s *taosSubscriber) Unsubscribe(keepProgress bool)`
取消订阅数据。
Unsubscribe from data.
#### schemaless
* `func (conn *Connector) InfluxDBInsertLines(lines []string, precision string) error`
写入 influxDB 行协议。
Write to influxDB line protocol.
* `func (conn *Connector) OpenTSDBInsertTelnetLines(lines []string) error`
写入 OpenTDSB telnet 协议数据。
Write OpenTDSB telnet protocol data.
* `func (conn *Connector) OpenTSDBInsertJsonPayload(payload string) error`
写入 OpenTSDB JSON 协议数据。
Writes OpenTSDB JSON protocol data.
#### 参数绑定
#### parameter binding
* `func (conn *Connector) StmtExecute(sql string, params *param.Param) (res driver.Result, err error)`
参数绑定单行插入。
Parameter bound single row insert.
* `func (conn *Connector) StmtQuery(sql string, params *param.Param) (rows driver.Rows, err error)`
参数绑定查询,返回 `database/sql/driver` 包的 `Rows` 结构。
Parameter bound query that returns the `Rows` structure of the `database/sql/driver` package.
* `func (conn *Connector) InsertStmt() *insertstmt.InsertStmt`
* `func (conn *Connector) InsertStmt() *insertstmt.
初始化参数。
Initialize the parameters.
* `func (stmt *InsertStmt) Prepare(sql string) error`
参数绑定预处理 SQL 语句。
Parameter binding preprocessing SQL statement.
* `func (stmt *InsertStmt) SetTableName(name string) error`
参数绑定设置表名。
Bind the set table name parameter.
* `func (stmt *InsertStmt) SetSubTableName(name string) error`
参数绑定设置子表名。
Parameter binding to set the sub table name.
* `func (stmt *InsertStmt) BindParam(params []*param.Param, bindType *param.ColumnType) error`
参数绑定多行数据。
Parameter bind multiple rows of data.
* `func (stmt *InsertStmt) AddBatch() error`
添加到参数绑定批处理。
Add to a parameter-bound batch.
* `func (stmt *InsertStmt) Execute() error`
执行参数绑定。
Execute a parameter binding.
* `func (stmt *InsertStmt) GetAffectedRows() int`
获取参数绑定插入受影响行数。
Gets the number of affected rows inserted by the parameter binding.
* `func (stmt *InsertStmt) Close() error`
结束参数绑定。
Closes the parameter binding.
## API 参考
## API Reference
全部 API [driver-go 文档](https://pkg.go.dev/github.com/taosdata/driver-go/v2)
Full API see [driver-go documentation](https://pkg.go.dev/github.com/taosdata/driver-go/v2)
\ No newline at end of file
......@@ -3,45 +3,45 @@ toc_max_heading_level: 4
sidebar_position: 2
sidebar_label: Java
title: TDengine Java Connector
description: TDengine Java 连接器基于标准 JDBC API 实现, 并提供原生连接与 REST连接两种连接器。
description: TDengine Java based on JDBC API and provide both native and REST connections
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
`taos-jdbcdriver` 是 TDengine 的官方 Java 语言连接器,Java 开发人员可以通过它开发存取 TDengine 数据库的应用软件。`taos-jdbcdriver` 实现了 JDBC driver 标准的接口,并提供两种形式的连接器。一种是通过 TDengine 客户端驱动程序(taosc)原生连接 TDengine 实例,支持数据写入、查询、订阅、schemaless 接口和参数绑定接口等功能,一种是通过 taosAdapter 提供的 REST 接口连接 TDengine 实例(2.0.18 及更高版本)。REST 连接实现的功能集合和原生连接有少量不同。
'taos-jdbcdriver' is TDengine's official Java language connector, which allows Java developers to develop applications that access the TDengine database. 'taos-jdbcdriver' implements the interface of the JDBC driver standard and provides two forms of connectors. One is to connect to a TDengine instance natively through the TDengine client driver (taosc), which supports functions such as data writing, querying, subscription, schemaless interface, and parameter binding interface. And the other is to connect to a TDengine instance through the REST interface provided by taosAdapter (2.0.18 and later). Rest connections implement small differences between the set of features implemented and native connections.
![tdengine-connector](tdengine-jdbc-connector.png)
! [tdengine-connector] (tdengine-jdbc-connector.png)
上图显示了两种 Java 应用使用连接器访问 TDengine 的两种方式:
The preceding diagram shows two ways for a Java app to access TDengine using connectors:
- JDBC 原生连接:Java 应用在物理节点 1(pnode1)上使用 TSDBDriver 直接调用客户端驱动(libtaos.so 或 taos.dll)的 API 将写入和查询请求发送到位于物理节点 2(pnode2)上的 taosd 实例。
- JDBC REST 连接:Java 应用通过 RestfulDriver 将 SQL 封装成一个 REST 请求,发送给物理节点 2 的 REST 服务器(taosAdapter),通过 REST 服务器请求 taosd 并返回结果。
- JDBC native connectivity: Java applications use TSDBDriver on physical node 1 (pnode1) to call client-driven directly (libtaos.so or taos.dll) APIs to send writing and query requests to taosd instances located on physical node 2 (pnode2).
- JDBC REST connection: The Java application encapsulates the SQL as a REST request via RestfulDriver, sends it to the REST server of physical node 2 (taosAdapter), requests taosd through the REST server, and returns the result.
使用 REST 连接,不依赖 TDengine 客户端驱动,可以跨平台,更加方便灵活,但性能比原生连接器低约 30%。
Using REST connectivity, which does not rely on TDengine client drivers, can be cross-platform, more convenient, and flexible but has about 30% lower performance than native connectors.
:::info
TDengine 的 JDBC 驱动实现尽可能与关系型数据库驱动保持一致,但 TDengine 与关系对象型数据库的使用场景和技术特征存在差异,所以`taos-jdbcdriver` 与传统的 JDBC driver 也存在一定差异。在使用时需要注意以下几点:
TDengine's JDBC driver implementation is as consistent as possible with the relational database driver. Still, there are differences in the use scenarios and technical characteristics of TDengine and relational object databases, so 'taos-jdbcdriver' also has some differences from traditional JDBC drivers. You need to pay attention to the following points when using:
- TDengine 目前不支持针对单条数据记录的删除操作。
- 目前不支持事务操作。
- TDengine does not currently support delete operations for individual data records.
- Transactional operations are not currently supported.
:::
## 支持的平台
## Supported platforms
原生连接支持的平台和 TDengine 客户端驱动支持的平台一致。
REST 连接支持所有能运行 Java 的平台。
Native connectivity supports the same platform as TDengine client-driven support.
REST connectivity supports all platforms that can run Java.
## 版本支持
## Version support
请参考[版本支持列表](/reference/connector#版本支持)
Please refer to [Version Support List] (/reference/connector# version support)
## TDengine DataType Java DataType
## TDengine DataType vs. Java DataType
TDengine 目前支持时间戳、数字、字符、布尔类型,与 Java 对应类型转换如下:
TDengine currently supports timestamp, number, character, Boolean type, and the corresponding type conversion with Java is as follows:
| TDengine DataType | JDBCType (driver 版本 < 2.0.24) | JDBCType (driver 版本 >= 2.0.24) |
| TDengine DataType | JDBCType (driver version < 2.0.24) | JDBCType (driver version > = 2.0.24) |
| ----------------- | --------------------------------- | ---------------------------------- |
| TIMESTAMP | java.lang.Long | java.sql.Timestamp |
| INT | java.lang.Integer | java.lang.Integer |
......@@ -55,29 +55,17 @@ TDengine 目前支持时间戳、数字、字符、布尔类型,与 Java 对
| NCHAR | java.lang.String | java.lang.String |
| JSON | - | java.lang.String |
**注意**:JSON 类型仅在 tag 中支持。
In the above example, JDBC uses the client's configuration file to establish a connection to a hostname of cluster_node1, port 6030, and a database named test. When the firstEp node fails, JDBC attempts to connect to the cluster using secondEp.
## 安装步骤
In TDengine, as long as one node in firstEp and secondEp is valid, the connection to the cluster can be established and worked.
### 安装前准备
使用 Java Connector 连接数据库前,需要具备以下条件:
- 已安装 Java 1.8 或以上版本运行时环境和 Maven 3.6 或以上版本
- 已安装 TDengine 客户端驱动(使用原生连接必须安装,使用 REST 连接无需安装),具体步骤请参考[安装客户端驱动](/reference/connector#安装客户端驱动)
### 安装连接器
<Tabs defaultValue="maven">
<TabItem value="maven" label="使用 Maven 安装">
目前 taos-jdbcdriver 已经发布到 [Sonatype Repository](https://search.maven.org/artifact/com.taosdata.jdbc/taos-jdbcdriver) 仓库,且各大仓库都已同步。
> **Note**: The configuration file here refers to the configuration file on the machine where the application that calls the JDBC Connector is located, the default value of /etc/taos/taos .cfg on Linux OS, and the default value of C://TDengine/cfg/taos.cfg on Windows OS.
- [sonatype](https://search.maven.org/artifact/com.taosdata.jdbc/taos-jdbcdriver)
- [mvnrepository](https://mvnrepository.com/artifact/com.taosdata.jdbc/taos-jdbcdriver)
- [maven.aliyun](https://maven.aliyun.com/mvn/search)
Maven 项目中,在 pom.xml 中添加以下依赖:
Add following dependency in the pom.xml file of your Maven project:
```xml-dtd
<dependency>
......@@ -88,9 +76,9 @@ Maven 项目中,在 pom.xml 中添加以下依赖:
```
</TabItem>
<TabItem value="source" label="使用源码编译安装">
<TabItem value="source" label="Build from source code">
可以通过下载 TDengine 的源码,自己编译最新版本的 Java connector
You can build Java connector from source code after clone TDengine project:
```shell
git clone https://github.com/taosdata/TDengine.git
......@@ -98,17 +86,17 @@ cd TDengine/src/connector/jdbc
mvn clean install -Dmaven.test.skip=true
```
编译后,在 target 目录下会产生 taos-jdbcdriver-2.0.XX-dist.jar 的 jar 包,并自动将编译的 jar 文件放在本地的 Maven 仓库中。
After compilation, a jar package of taos-jdbcdriver-2.0.XX-dist .jar is generated in the target directory, and the compiled jar file is automatically placed in the local Maven repository.
</TabItem>
</Tabs>
## 建立连接
## Establish a connection
TDengine 的 JDBC URL 规范格式为:
`jdbc:[TAOS|TAOS-RS]://[host_name]:[port]/[database_name]?[user={user}|&password={password}|&charset={charset}|&cfgdir={config_dir}|&locale={locale}|&timezone={timezone}]`
TDengine's JDBC URL specification format is:
`jdbc:[TAOS| TAOS-RS]://[host_name]:[port]/[database_name]? [user={user}|&password={password}|&charset={charset}|&cfgdir={config_dir}|&locale={locale}|&timezone={timezone}]`
对于建立连接,原生连接与 REST 连接有细微不同。
For establishing connections, native connections differ slightly from REST connections.
<Tabs defaultValue="native">
<TabItem value="native" label="原生连接">
......@@ -119,28 +107,28 @@ String jdbcUrl = "jdbc:TAOS://taosdemo.com:6030/test?user=root&password=taosdata
Connection conn = DriverManager.getConnection(jdbcUrl);
```
以上示例,使用了 JDBC 原生连接的 TSDBDriver,建立了到 hostname 为 taosdemo.com,端口为 6030(TDengine 的默认端口),数据库名为 test 的连接。这个 URL 中指定用户名(user)为 root,密码(password)为 taosdata。
In the above example, TSDBDriver, which uses a JDBC native connection, establishes a connection to a hostname of taosdemo.com, port 6030 (the default port for TDengine), and a database named test. In this URL, the user name (user) is specified as root, and the password (password) is taosdata.
**注意**:使用 JDBC 原生连接,taos-jdbcdriver 需要依赖客户端驱动(Linux 下是 libtaos.so;Windows 下是 taos.dll)。
Note: With JDBC native connections, taos-jdbcdriver relies on the client driver (libtaos.so under Linux; taos .dll under Windows).
url 中的配置参数如下:
The configuration parameters in the URL are as follows:
- user:登录 TDengine 用户名,默认值 'root'。
- password:用户登录密码,默认值 'taosdata'。
- cfgdir:客户端配置文件目录路径,Linux OS 上默认值 `/etc/taos`,Windows OS 上默认值 `C:/TDengine/cfg`。
- charset:客户端使用的字符集,默认值为系统字符集。
- locale:客户端语言环境,默认值系统当前 locale。
- timezone:客户端使用的时区,默认值为系统当前时区。
- batchfetch: true:在执行查询时批量拉取结果集;false:逐行拉取结果集。默认值为:false。开启批量拉取同时获取一批数据在查询数据量较大时批量拉取可以有效的提升查询性能。
- batchErrorIgnore:true:在执行 Statement 的 executeBatch 时,如果中间有一条 SQL 执行失败将继续执行下面的 SQL。false:不再执行失败 SQL 后的任何语句。默认值为:false。
- user: Log in to the TDengine username. The default value is 'root'.
- password: User login password, the default value is 'taosdata'.
- cfgdir: client configuration file directory path, default '/etc/taos' on Linux OS, 'C:/TDengine/cfg' on Windows OS.
- charset: The character set used by the client, the default value is the system character set.
- locale: Client locale, by default, use the system's current locale.
- timezone: The time zone used by the client, the default value is the system's current time zone.
- batchfetch: true: pulls result sets in batches when executing queries; false: pulls result sets row by row. The default value is: false. Enabling batch pull and obtaining a batch of data can improve query performance when the query data volume is large.
- batchErrorIgnore:true: When executing statement executeBatch, if there is a SQL execution failure in the middle, the following SQL will continue to be executed. false: No more statements after the failed SQL are executed. The default value is: false.
JDBC 原生连接的使用请参见[视频教程](https://www.taosdata.com/blog/2020/11/11/1955.html)。
For more information about JDBC native connections, see [Video Tutorial] (https://www.taosdata.com/blog/2020/11/11/1955.html).
**使用 TDengine 客户端驱动配置文件建立连接 **
**Connect using the TDengine client-driven configuration file **
当使用 JDBC 原生连接连接 TDengine 集群时,可以使用 TDengine 客户端驱动配置文件,在配置文件中指定集群的 firstEp、secondEp 等参数。如下所示:
When you use a JDBC native connection to connect to a TDengine cluster, you can use the TDengine client-driven configuration file to specify parameters such as firstEp and secondEp of the cluster in the configuration file as below:
1. 在 Java 应用中不指定 hostname 和 port
1. Do not specify hostname and port in Java applications.
```java
public Connection getConn() throws Exception{
......@@ -155,7 +143,7 @@ public Connection getConn() throws Exception{
}
```
2. 在配置文件中指定 firstEp 和 secondEp
2. specify the firstEp and the secondEp in the configuration file taos.cfg
```shell
# first fully qualified domain name (FQDN) for TDengine system
......@@ -171,11 +159,11 @@ secondEp cluster_node2:6030
# locale en_US.UTF-8
```
以上示例,jdbc 会使用客户端的配置文件,建立到 hostname 为 cluster_node1、端口为 6030、数据库名为 test 的连接。当集群中 firstEp 节点失效时,JDBC 会尝试使用 secondEp 连接集群。
In the above example, JDBC uses the client's configuration file to establish a connection to a hostname of cluster_node1, port 6030, and a database named test. When the firstEp node in the cluster fails, JDBC attempts to connect to the cluster using secondEp.
TDengine 中,只要保证 firstEp 和 secondEp 中一个节点有效,就可以正常建立到集群的连接。
In TDengine, as long as one node in firstEp and secondEp is valid, the connection to the cluster can be established normally.
> **注意**:这里的配置文件指的是调用 JDBC Connector 的应用程序所在机器上的配置文件,Linux OS 上默认值 /etc/taos/taos.cfg ,Windows OS 上默认值 C://TDengine/cfg/taos.cfg。
> **Note**: The configuration file here refers to the configuration file on the machine where the application that calls the JDBC Connector is located, the default value of /etc/taos/taos .cfg on Linux OS, and the default value of C://TDengine/cfg/taos.cfg on Windows OS.
</TabItem>
<TabItem value="rest" label="REST 连接">
......@@ -186,46 +174,46 @@ String jdbcUrl = "jdbc:TAOS-RS://taosdemo.com:6041/test?user=root&password=taosd
Connection conn = DriverManager.getConnection(jdbcUrl);
```
以上示例,使用了 JDBC REST 连接的 RestfulDriver,建立了到 hostname 为 taosdemo.com,端口为 6041,数据库名为 test 的连接。这个 URL 中指定用户名(user)为 root,密码(password)为 taosdata。
In the above example, a RestfulDriver with a JDBC REST connection is used to establish a connection to a database named test with hostname taosdemo.com on port 6041. The URL specifies the user name (user) as root and the password (password) as taosdata.
使用 JDBC REST 连接,不需要依赖客户端驱动。与 JDBC 原生连接相比,仅需要:
There is no dependency on the client driver when Using a JDBC REST connection. Compared to a JDBC native connection, only the following are required: 1.
1. driverClass 指定为“com.taosdata.jdbc.rs.RestfulDriver”;
2. jdbcUrl 以“jdbc:TAOS-RS://”开头;
3. 使用 6041 作为连接端口。
1. driverClass specified as "com.taosdata.jdbc.rs.RestfulDriver".
2. jdbcUrl starting with "jdbc:TAOS-RS://". 3.
3. use 6041 as the connection port.
url 中的配置参数如下:
The configuration parameters in the URL are as follows.
- user:登录 TDengine 用户名,默认值 'root'。
- password:用户登录密码,默认值 'taosdata'。
- batchfetch: true:在执行查询时批量拉取结果集;false:逐行拉取结果集。默认值为:false。逐行拉取结果集使用 HTTP 方式进行数据传输。从 taos-jdbcdriver-2.0.38 和 TDengine 2.4.0.12 版本开始,JDBC REST 连接增加批量拉取数据功能。taos-jdbcdriver 与 TDengine 之间通过 WebSocket 连接进行数据传输。相较于 HTTP,WebSocket 可以使 JDBC REST 连接支持大数据量查询,并提升查询性能。
- batchErrorIgnore:true:在执行 Statement 的 executeBatch 时,如果中间有一条 SQL 执行失败,继续执行下面的 SQL 了。false:不再执行失败 SQL 后的任何语句。默认值为:false。
- user: Login TDengine user name, default value 'root'.
- password: user login password, default value 'taosdata'.
- batchfetch: true: pull the result set in batch when executing the query; false: pull the result set row by row. The default value is false. batchfetch uses HTTP for data transfer. The JDBC REST connection supports bulk data pulling function in taos-jdbcdriver-2.0.38 and TDengine 2.4.0.12 and later versions. taos-jdbcdriver and TDengine transfer data via WebSocket connection. Compared with HTTP, WebSocket enables JDBC REST connection to support large data volume querying and improve query performance.
- batchErrorIgnore: true: when executing executeBatch of Statement, if one SQL execution fails in the middle, continue to execute the following SQL. false: no longer execute any statement after the failed SQL. The default value is: false.
**注意**:部分配置项(比如:locale、timezone)在 REST 连接中不生效。
**Note**: Some configuration items (e.g., locale, timezone) do not work in the REST connection.
:::note
- 与原生连接方式不同,REST 接口是无状态的。在使用 JDBC REST 连接时,需要在 SQL 中指定表、超级表的数据库名称。例如:
- Unlike the native connection method, the REST interface is stateless. When using the JDBC REST connection, you need to specify the database name of the table and super table in SQL. For example.
```sql
INSERT INTO test.t1 USING test.weather (ts, temperature) TAGS('beijing') VALUES(now, 24.6);
```
- 从 taos-jdbcdriver-2.0.36 和 TDengine 2.2.0.0 版本开始,如果在 url 中指定了 dbname,那么,JDBC REST 连接会默认使用/rest/sql/dbname 作为 restful 请求的 url,在 SQL 中不需要指定 dbname。例如:url 为 jdbc:TAOS-RS://127.0.0.1:6041/test,那么,可以执行 sql:insert into t1 using weather(ts, temperature) tags('beijing') values(now, 24.6);
- Starting from taos-jdbcdriver-2.0.36 and TDengine 2.2.0.0, if dbname is specified in the url, JDBC REST connections will use /rest/sql/dbname as the url for restful requests by default, and there is no need to specify dbname in SQL. For example, if the url is jdbc:TAOS-RS://127.0.0.1:6041/test, then the sql can be executed: insert into t1 using weather(ts, temperature) tags('beijing') values(now, 24.6);
:::
</TabItem>
</Tabs>
### 指定 URL 和 Properties 获取连接
### Specify the URL and Properties to get the connection
除了通过指定的 URL 获取连接,还可以使用 Properties 指定建立连接时的参数。
In addition to getting the connection from the specified URL, you can use Properties to specify parameters when the connection is established.
**注意**:
**Note**:
- 应用中设置的 client parameter 为进程级别的,即如果要更新 client 的参数,需要重启应用。这是因为 client parameter 是全局参数,仅在应用程序的第一次设置生效。
- 以下示例代码基于 taos-jdbcdriver-2.0.36。
- The client parameter set in the application is process-level. If you want to update the parameters of the client, you need to restart the application. This is because the client parameter is a global parameter that takes effect only the first time the application is set.
- The following sample code is based on taos-jdbcdriver-2.0.36.
```java
public Connection getConn() throws Exception{
......@@ -251,33 +239,33 @@ public Connection getRestConn() throws Exception{
}
```
以上示例,建立一个到 hostname 为 taosdemo.com,端口为 6030/6041,数据库名为 test 的连接。这个连接在 url 中指定了用户名(user)为 root,密码(password)为 taosdata,并在 connProps 中指定了使用的字符集、语言环境、时区、是否开启批量拉取等信息。
In the above example, a connection is established to taosdemo.com with hostname taosdemo.com, port 6030/6041, and database named test. The connection specifies the user name (user) as root and the password (password) as taosdata in the URL and specifies the character set, language environment, time zone, and whether to enable bulk fetching in the connProps.
properties 中的配置参数如下:
The configuration parameters in properties are as follows.
- TSDBDriver.PROPERTY_KEY_USER:登录 TDengine 用户名,默认值 'root'。
- TSDBDriver.PROPERTY_KEY_PASSWORD:用户登录密码,默认值 'taosdata'。
- TSDBDriver.PROPERTY_KEY_BATCH_LOAD: true:在执行查询时批量拉取结果集;false:逐行拉取结果集。默认值为:false。
- TSDBDriver.PROPERTY_KEY_BATCH_ERROR_IGNORE:true:在执行 Statement 的 executeBatch 时,如果中间有一条 SQL 执行失败,继续执行下面的 sq 了。false:不再执行失败 SQL 后的任何语句。默认值为:false。
- TSDBDriver.PROPERTY_KEY_CONFIG_DIR:仅在使用 JDBC 原生连接时生效。客户端配置文件目录路径,Linux OS 上默认值 `/etc/taos`,Windows OS 上默认值 `C:/TDengine/cfg`。
- TSDBDriver.PROPERTY_KEY_CHARSET:仅在使用 JDBC 原生连接时生效。 客户端使用的字符集,默认值为系统字符集。
- TSDBDriver.PROPERTY_KEY_LOCALE:仅在使用 JDBC 原生连接时生效。 客户端语言环境,默认值系统当前 locale。
- TSDBDriver.PROPERTY_KEY_TIME_ZONE:仅在使用 JDBC 原生连接时生效。 客户端使用的时区,默认值为系统当前时区。
- 此外对 JDBC 原生连接,通过指定 URL 和 Properties 还可以指定其他参数,比如日志级别、SQL 长度等。更多详细配置请参考[客户端配置](/reference/config/#仅客户端适用)。
- TSDBDriver.PROPERTY_KEY_USER: Login TDengine user name, default value 'root'.
- TSDBDriver.PROPERTY_KEY_PASSWORD: user login password, default value 'tasdata'.
- TSDBDriver.PROPERTY_KEY_BATCH_LOAD: true: pull the result set in batch when executing query; false: pull the result set row by row. The default value is: false.
- TSDBDriver.PROPERTY_KEY_BATCH_ERROR_IGNORE: true: when executing executeBatch of Statement, if there is a SQL execution failure in the middle, continue to execute the following sq. false: no longer execute any statement after the failed SQL. The default value is: false.
- TSDBDriver.PROPERTY_KEY_CONFIG_DIR: Only works when using JDBC native connection. Client configuration file directory path, default value `/etc/taos` on Linux OS, default value `C:/TDengine/cfg` on Windows OS.
- TSDBDriver.PROPERTY_KEY_CHARSET: takes effect only when using JDBC native connection. In the character set used by the client, the default value is the system character set.
- TSDBDriver.PROPERTY_KEY_LOCALE: this only takes effect when using JDBC native connection. Client language environment, the default value is system current locale.
- TSDBDriver.PROPERTY_KEY_TIME_ZONE: only takes effect when using JDBC native connection. In the time zone used by the client, the default value is the system's current time zone.
For JDBC native connections, you can specify other parameters, such as log level, SQL length, etc., by specifying URL and Properties. For more detailed configuration, please refer to [Client Configuration](/reference/config/#Client only).
### 配置参数的优先级
### Priority of configuration parameters
通过前面三种方式获取连接,如果配置参数在 url、Properties、客户端配置文件中有重复,则参数的`优先级由高到低`分别如下:
If the configuration parameters are duplicated in the URL, Properties, or client configuration file, the `priority` of the parameters, from highest to lowest, are as follows.
1. JDBC URL 参数,如上所述,可以在 JDBC URL 的参数中指定。
1. JDBC URL parameters, as described above, can be specified in the parameters of the JDBC URL.
2. Properties connProps
3. 使用原生连接时,TDengine 客户端驱动的配置文件 taos.cfg
3. the configuration file taos.cfg of the TDengine client driver when using a native connection
例如:在 url 中指定了 password 为 taosdata,在 Properties 中指定了 password 为 taosdemo,那么,JDBC 会使用 url 中的 password 建立连接。
For example, if you specify the password as `taosdata` in the URL and specify the password as `taosdemo` in the Properties simultaneously. In this case, JDBC will use the password in the URL to establish the connection.
## 使用示例
## Usage examples
### 创建数据库和表
### Create database and tables
```java
Statement stmt = conn.createStatement();
......@@ -292,9 +280,9 @@ stmt.executeUpdate("use db");
stmt.executeUpdate("create table if not exists tb (ts timestamp, temperature int, humidity float)");
```
> **注意**:如果不使用 `use db` 指定数据库,则后续对表的操作都需要增加数据库名称作为前缀,如 db.tb。
> **Note**: If you do not use `use db` to specify the database, all subsequent operations on the table need to add the database name as a prefix, such as db.tb.
### 插入数据
### Insert data
```java
// insert data
......@@ -303,10 +291,10 @@ int affectedRows = stmt.executeUpdate("insert into tb values(now, 23, 10.3) (now
System.out.println("insert " + affectedRows + " rows.");
```
> now 为系统内部函数,默认为客户端所在计算机当前时间。
> `now + 1s` 代表客户端当前时间往后加 1 秒,数字后面代表时间单位:a(毫秒),s(秒),m(分),h(小时),d(天),w(周),n(月),y(年)。
> now is an internal function. The default is the current time of the client's computer.
> `now + 1s` represents the current time of the client plus 1 second, followed by the number representing the unit of time: a (milliseconds), s (seconds), m (minutes), h (hours), d (days), w (weeks), n (months), y (years).
### 查询数据
### Querying data
```java
// query data
......@@ -325,11 +313,11 @@ while(resultSet.next()){
}
```
> 查询和操作关系型数据库一致,使用下标获取返回字段内容时从 1 开始,建议使用字段名称获取。
> The query is consistent with operating a relational database. When using subscripts to get the contents of the returned fields, starting from 1, it is recommended to use the field names to get them.
### 处理异常
### Handling exceptions
在报错后,通过 SQLException 可以获取到错误的信息和错误码:
After an error is reported, the error message and error code can be obtained through SQLException.
```java
try (Statement statement = connection.createStatement()) {
......@@ -344,23 +332,27 @@ try (Statement statement = connection.createStatement()) {
}
```
JDBC 连接器可能报错的错误码包括 3 种:JDBC driver 本身的报错(错误码在 0x2301 到 0x2350 之间),原生连接方法的报错(错误码在 0x2351 到 0x2400 之间),TDengine 其他功能模块的报错。
There are three types of error codes that the JDBC connector can report:
- Error code of the JDBC driver itself (error code between 0x2301 and 0x2350)
- Error code of the native connection method (error code between 0x2351 and 0x2400)
- Error code of other TDengine function modules
具体的错误码请参考:
For specific error codes, please refer to.
- [TDengine Java Connector](https://github.com/taosdata/TDengine/blob/develop/src/connector/jdbc/src/main/java/com/taosdata/jdbc/TSDBErrorNumbers.java)
- [TDengine Java Connector](https://github.com/taosdata/TDengine/blob/develop/src/connector/jdbc/src/main/java/com/taosdata/jdbc/ TSDBErrorNumbers.java)
- [TDengine_ERROR_CODE](https://github.com/taosdata/TDengine/blob/develop/src/inc/taoserror.h)
### 通过参数绑定写入数据
### Writing data via parameter binding
从 2.1.2.0 版本开始,TDengine 的 JDBC 原生连接实现大幅改进了参数绑定方式对数据写入(INSERT)场景的支持。采用这种方式写入数据时,能避免 SQL 语法解析的资源消耗,从而在很多情况下显著提升写入性能。
TDengine's native JDBC connection implementation has significantly improved its support for data writing (INSERT) scenarios via parameter binding with version 2.1.2.0 and later versions. Writing data in this way avoids the resource consumption of SQL syntax parsing, resulting in significant write performance improvements in many cases.
**注意**:
**Note**.
- JDBC REST 连接目前不支持参数绑定
- 以下示例代码基于 taos-jdbcdriver-2.0.36
- binary 类型数据需要调用 setString 方法,nchar 类型数据需要调用 setNString 方法
- setString 和 setNString 都要求用户在 size 参数里声明表定义中对应列的列宽
- JDBC REST connections do not currently support parameter binding
- The following sample code is based on taos-jdbcdriver-2.0.36
- The setString method should be called for binary type data, and the setNString method should be called for nchar type data
- both setString and setNString require the user to declare the width of the corresponding column in the size parameter of the table definition
```java
public class ParameterBindingDemo {
......@@ -588,7 +580,7 @@ public class ParameterBindingDemo {
}
```
用于设定 TAGS 取值的方法总共有:
The methods to set TAGS values:
```java
public void setTagNull(int index, int type)
......@@ -604,7 +596,7 @@ public void setTagString(int index, String value)
public void setTagNString(int index, String value)
```
用于设定 VALUES 数据列的取值的方法总共有:
The methods to set VALUES columns:
```java
public void setInt(int columnIndex, ArrayList<Integer> list) throws SQLException
......@@ -619,14 +611,14 @@ public void setString(int columnIndex, ArrayList<String> list, int size) throws
public void setNString(int columnIndex, ArrayList<String> list, int size) throws SQLException
```
### 无模式写入
### Writing without mode
从 2.2.0.0 版本开始,TDengine 增加了对无模式写入功能。无模式写入兼容 InfluxDB 的 行协议(Line Protocol)、OpenTSDB 的 telnet 行协议和 OpenTSDB 的 JSON 格式协议。详情请参见[无模式写入](/reference/schemaless/)。
Starting with version 2.2.0.0, TDengine has added the ability to write without mode. It is compatible with InfluxDB's Line Protocol, OpenTSDB's telnet line protocol, and OpenTSDB's JSON format protocol. See [schemaless writing](/reference/schemaless/) for details.
**注意**:
**Note**.
- JDBC REST 连接目前不支持无模式写入
- 以下示例代码基于 taos-jdbcdriver-2.0.36
- JDBC REST connections do not currently support schemaless writes
- The following sample code is based on taos-jdbcdriver-2.0.36
```java
public class SchemalessInsertTest {
......@@ -657,25 +649,25 @@ public class SchemalessInsertTest {
}
```
### 订阅
### Subscriptions
TDengine Java 连接器支持订阅功能,应用 API 如下:
The TDengine Java Connector supports subscription functionality with the following application API.
#### 创建订阅
#### Create subscriptions
```java
TSDBSubscribe sub = ((TSDBConnection)conn).subscribe("topic", "select * from meters", false);
```
`subscribe` 方法的三个参数含义如下:
The three parameters of the `subscribe` method have the following meanings.
- topic:订阅的主题(即名称),此参数是订阅的唯一标识
- sql:订阅的查询语句,此语句只能是 `select` 语句,只应查询原始数据,只能按时间正序查询数据
- restart:如果订阅已经存在,是重新开始,还是继续之前的订阅
- topic: the subscribed topic (i.e., name). This parameter is the unique identifier of the subscription
- sql: the query statement of the subscription, this statement can only be `select` statement, only the original data should be queried, and you can query only the data in the positive time order
- restart: if the subscription already exists, whether to restart or continue the previous subscription
如上面的例子将使用 SQL 语句 `select * from meters` 创建一个名为 `topic` 的订阅,如果这个订阅已经存在,将继续之前的查询进度,而不是从头开始消费所有的数据。
The above example will use the SQL statement `select * from meters` to create a subscription named `topic`. If the subscription exists, it will continue the progress of the previous query instead of consuming all the data from the beginning.
#### 订阅消费数据
#### Subscribe to consume data
```java
int total = 0;
......@@ -691,17 +683,17 @@ while(true) {
}
```
`consume` 方法返回一个结果集,其中包含从上次 `consume` 到目前为止的所有新数据。请务必按需选择合理的调用 `consume` 的频率(如例子中的 `Thread.sleep(1000)`),否则会给服务端造成不必要的压力。
The `consume` method returns a result set containing all new data from the last `consume`. Be sure to choose a reasonable frequency for calling `consume` as needed (e.g. `Thread.sleep(1000)` in the example). Otherwise, it will cause unnecessary stress on the server-side.
#### 关闭订阅
#### Close subscriptions
```java
sub.close(true);
```
`close` 方法关闭一个订阅。如果其参数为 `true` 表示保留订阅进度信息,后续可以创建同名订阅继续消费数据;如为 `false` 则不保留订阅进度。
The ``close`` method closes a subscription. If its argument is ``true`'' it means that the subscription progress information is retained, and the subscription with the same name can be created to continue consuming data; if it is ``false`'' it does not retain the subscription progress.
### 关闭资源
### Closing resources
```java
resultSet.close();
......@@ -709,13 +701,13 @@ stmt.close();
conn.close();
```
> `注意务必要将 connection 进行关闭`,否则会出现连接泄露。
> ``Be sure to close the connection``, otherwise, there will be a connection leak.
### 与连接池使用
### Use with connection pools
#### HikariCP
使用示例如下:
Example usage is as follows.
```java
public static void main(String[] args) throws SQLException {
......@@ -744,12 +736,12 @@ conn.close();
}
```
> 通过 HikariDataSource.getConnection() 获取连接后,使用完成后需要调用 close() 方法,实际上它并不会关闭连接,只是放回连接池中。
> 更多 HikariCP 使用问题请查看[官方说明](https://github.com/brettwooldridge/HikariCP)。
> getConnection(), you need to call the close() method after you finish using it. It doesn't close the connection. It just puts it back into the connection pool.
> For more questions about using HikariCP, please see the [official instructions](https://github.com/brettwooldridge/HikariCP).
#### Druid
使用示例如下:
Example usage is as follows.
```java
public static void main(String[] args) throws Exception {
......@@ -776,64 +768,64 @@ public static void main(String[] args) throws Exception {
}
```
> 更多 druid 使用问题请查看[官方说明](https://github.com/alibaba/druid)。
> For more questions about using druid, please see [Official Instructions](https://github.com/alibaba/druid).
**注意事项:**
**Caution:**
- TDengine `v1.6.4.1` 版本开始提供了一个专门用于心跳检测的函数 `select server_status()`,所以在使用连接池时推荐使用 `select server_status()` 进行 Validation Query。
- TDengine `v1.6.4.1` provides a special function `select server_status()` for heartbeat detection, so it is recommended to use `select server_status()` for Validation Query when using connection pooling.
如下所示,`select server_status()` 执行成功会返回 `1`。
As you can see below, `select server_status()` returns `1` on successful execution.
```sql
taos> select server_status();
server_status()|
================
1 |
1 |
Query OK, 1 row(s) in set (0.000141s)
```
### 更多示例程序
### More sample programs
示例程序源码位于 `TDengine/examples/JDBC` 下:
The source code of the sample application is under `TDengine/examples/JDBC`:
- JDBCDemo:JDBC 示例源程序。
- JDBCConnectorChecker:JDBC 安装校验源程序及 jar 包。
- connectionPools:HikariCP, Druid, dbcp, c3p0 等连接池中使用 taos-jdbcdriver。
- SpringJdbcTemplate:Spring JdbcTemplate 中使用 taos-jdbcdriver。
- mybatisplus-demo:Springboot + Mybatis 中使用 taos-jdbcdriver。
- JDBCDemo: JDBC sample source code.
- JDBCConnectorChecker: JDBC installation checker source and jar package.
- connectionPools: using taos-jdbcdriver in connection pools such as HikariCP, Druid, dbcp, c3p0, etc.
- SpringJdbcTemplate: using taos-jdbcdriver in Spring JdbcTemplate.
- mybatisplus-demo: using taos-jdbcdriver in Springboot + Mybatis.
请参考:[JDBC example](https://github.com/taosdata/TDengine/tree/develop/examples/JDBC)
Please refer to: [JDBC example](https://github.com/taosdata/TDengine/tree/develop/examples/JDBC)
## 重要更新记录
## Important update logs
| taos-jdbcdriver 版本 | 主要变化 |
| taos-jdbcdriver version | major changes |
| :------------------: | :----------------------------: |
| 2.0.38 | JDBC REST 连接增加批量拉取功能 |
| 2.0.37 | 增加对 json tag 支持 |
| 2.0.36 | 增加对 schemaless 写入支持 |
| 2.0.38 | JDBC REST connections add bulk pull function |
| 2.0.37 | Added support for json tags |
| 2.0.36 | Add support for schemaless writing |
## 常见问题
## Frequently Asked Questions
1. 使用 Statement 的 `addBatch` 和 `executeBatch` 来执行“批量写入/更行”,为什么没有带来性能上的提升?
1. Why is there no performance improvement when using Statement's `addBatch` and `executeBatch` to perform `batch writes/reviews`?
**原因**:TDengine 的 JDBC 实现中,通过 `addBatch` 方法提交的 SQL 语句,会按照添加的顺序,依次执行,这种方式没有减少与服务端的交互次数,不会带来性能上的提升。
**Cause**: In TDengine's JDBC implementation, SQL statements submitted by `addBatch` method are executed sequentially in the order they are added, which does not reduce the number of interactions with the server and does not bring performance improvement.
**解决方法**:1. 在一条 insert 语句中拼接多个 values 值;2. 使用多线程的方式并发插入;3. 使用参数绑定的写入方式
**Solution**: 1. splice multiple values in a single insert statement; 2. use multi-threaded concurrent insertion; 3. use parameter-bound writing
2. java.lang.UnsatisfiedLinkError: no taos in java.library.path
**原因**:程序没有找到依赖的本地函数库 taos。
**Cause**: The program did not find the dependent native library taos.
**解决方法**:Windows 下可以将 C:\TDengine\driver\taos.dll 拷贝到 C:\Windows\System32\ 目录下,Linux 下将建立如下软链 `ln -s /usr/local/taos/driver/libtaos.so.x.x.x.x /usr/lib/libtaos.so` 即可。
**Solution**: Under Windows you can copy C:\TDengine\driver\taos.dll to the C:\Windows\System32\ directory, under Linux the following softlink will be created `ln -s /usr/local/taos/driver/libtaos.so.x.x. x.x /usr/lib/libtaos.so` will work.
3. java.lang.UnsatisfiedLinkError: taos.dll Can't load AMD 64 bit on a IA 32-bit platform
3. java.lang.UnsatisfiedLinkError: taos.dll Can't load AMD 64 bit on an IA 32-bit platform
**原因**:目前 TDengine 只支持 64 位 JDK。
**Cause**: Currently, TDengine only supports 64-bit JDK.
**解决方法**:重新安装 64 位 JDK。
**Solution**: Reinstall the 64-bit JDK. 4.
4. 其它问题请参考 [FAQ](/train-faq/faq)
For other questions, please refer to [FAQ](/train-faq/faq)
## API 参考
## API Reference
[taos-jdbcdriver doc](https://docs.taosdata.com/api/taos-jdbcdriver)
......@@ -8,69 +8,69 @@ description: "taospy 是 TDengine 的官方 Python 连接器。taospy 提供了
import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";
`taospy` 是 TDengine 的官方 Python 连接器。`taospy` 提供了丰富的 API, 使得 Python 应用可以很方便地使用 TDengine。`taospy` 对 TDengine 的[原生接口](/reference/connector/cpp)和 [REST 接口](/reference/rest-api)都进行了封装, 分别对应 `taospy` 包的 `taos` 模块 和 `taosrest` 模块。
除了对原生接口和 REST 接口的封装,`taospy` 还提供了符合 [Python 数据访问规范(PEP 249)](https://peps.python.org/pep-0249/) 的编程接口。这使得 `taospy` 和很多第三方工具集成变得简单,比如 [SQLAlchemy](https://www.sqlalchemy.org/) 和 [pandas](https://pandas.pydata.org/)。
`taospy` is the official Python connector for TDengine. `taospy` provides a rich API that makes it easy for Python applications to use TDengine. `taospy` wraps both the [native interface](/reference/connector/cpp) and [REST interface](/reference/rest-api) of TDengine, which correspond to the `taos` and `taosrest` modules of the `taospy` package, respectively.
In addition to wrapping the native and REST interfaces, `taospy` also provides a programming interface that conforms to the [Python Data Access Specification (PEP 249)](https://peps.python.org/pep-0249/). It is easy to integrate `taospy` with many third-party tools, such as [SQLAlchemy](https://www.sqlalchemy.org/) and [pandas](https://pandas.pydata.org/).
使用客户端驱动提供的原生接口直接与服务端建立的连接的方式下文中称为“原生连接”;使用 taosAdapter 提供的 REST 接口与服务端建立的连接的方式下文中称为“REST 连接”。
The connection to the server directly using the native interface provided by the client driver is referred to hereinafter as a "native connection"; the connection to the server using the REST interface provided by taosAdapter is referred to hereinafter as a "REST connection". ".
Python 连接器的源码托管在 [GitHub](https://github.com/taosdata/taos-connector-python)。
The source code for the Python connector is hosted on [GitHub](https://github.com/taosdata/taos-connector-python).
## 支持的平台
## Supported Platforms
- 原生连接[支持的平台](/reference/connector/#支持的平台)和 TDengine 客户端支持的平台一致。
- REST 连接支持所有能运行 Python 的平台。
- The native connection [supported platforms](/reference/connector/#supported-platforms) is the same as the one supported by the TDengine client.
- REST connections are supported on all platforms that can run Python.
## 版本选择
## Version selection
无论使用什么版本的 TDengine 都建议使用最新版本的 `taospy`。
We recommend using the latest version of `taospy`, regardless of the version of TDengine used.
## 支持的功能
## Supported features
- 原生连接支持 TDeingine 的所有核心功能, 包括: 连接管理、执行 SQL、参数绑定、订阅、无模式写入(schemaless)。
- REST 连接支持的功能包括:连接管理、执行 SQL。 (通过执行 SQL 可以: 管理数据库、管理表和超级表、写入数据、查询数据、创建连续查询等)。
- Native connections support all the core features of TDeingine, including connection management, SQL execution, parameter binding, subscriptions, and schemaless writing.
- REST connections support features such as connection management and SQL execution. (SQL execution allows you to: manage databases, tables, and supertables, write data, query data, create continuous queries, etc.).
## 安装
## Installation
### 准备
### Preparation
1. 安装 Python。建议使用 Python >= 3.6。如果系统上还没有 Python 可参考 [Python BeginnersGuide](https://wiki.python.org/moin/BeginnersGuide/Download) 安装。
2. 安装 [pip](https://pypi.org/project/pip/)。大部分情况下 Python 的安装包都自带了 pip 工具, 如果没有请参考 [pip docuemntation](https://pip.pypa.io/en/stable/installation/) 安装。
3. 如果使用原生连接,还需[安装客户端驱动](../#安装客户端驱动)。客户端软件包含了 TDengine 客户端动态链接库(libtaos.so 或 taos.dll) 和 TDengine CLI。
1. Install Python. Python >= 3.6 is recommended. If Python is not available on your system, refer to the [Python BeginnersGuide](https://wiki.python.org/moin/BeginnersGuide/Download) to install it. 2.
Install [pip](https://pypi.org/project/pip/). In most cases, the Python installer comes with the pip utility. If not, please refer to [pip docuemntation](https://pip.pypa.io/en/stable/installation/) to install it.
If you use a native connection, you will also need to [install the client driver](...). /#install client driver). The client software contains the TDengine client dynamic link library (libtaos.so or taos.dll) and the TDengine CLI.
### 使用 pip 安装
### Install using pip
#### 卸载旧版本
#### Uninstalling an older version
如果以前安装过旧版本的 Python 连接器, 请提前卸载。
If you have previously installed an older version of the Python Connector, please uninstall it beforehand.
```
pip3 uninstall taos taospy
```
:::note
较早的 TDengine 客户端软件包含了 Python 连接器。如果从客户端软件的安装目录安装了 Python 连接器,那么对应的 Python 包名是 `taos`。 所以上述卸载命令包含了 `taos`, 不存在也没关系。
Earlier TDengine client software includes the Python connector. If the Python connector is installed from the client software's installation directory, the corresponding Python package name is `taos`. So the above uninstall command includes `taos`, and it doesn't matter if it doesn't exist.
:::
#### 安装 `taospy`
#### to install `taospy`
<Tabs>
<TabItem label="从 PyPI 安装" value="pypi">
<TabItem label="Install from PyPI" value="pypi">
安装最新版本
Install the latest version of
```
pip3 install taospy
```
也可以指定某个特定版本安装。
You can also specify a specific version to install.
```
pip3 install taospy==2.3.0
```
</TabItem>
<TabItem label="从 GitHub 安装" value="github">
</TabItem
<TabItem label="Install from GitHub" value="github">
```
pip3 install git+https://github.com/taosdata/taos-connector-python.git
......@@ -79,21 +79,21 @@ pip3 install git+https://github.com/taosdata/taos-connector-python.git
</TabItem>
</Tabs>
### 安装验证
### Installation verification
<Tabs groupId="connect" default="native">
<TabItem value="native" label="原生连接">
<TabItem value="native" label="native connection">
对于原生连接,需要验证客户端驱动和 Python 连接器本身是否都正确安装。如果能成功导入 `taos` 模块,则说明已经正确安装了客户端驱动和 Python 连接器。可在 Python 交互式 Shell 中输入:
For native connections, you need to verify that both the client driver and the Python connector itself are installed correctly. The client driver and Python connector have been installed properly if you can successfully import the `taos` module. In the Python Interactive Shell, you can type.
```python
import taos
```
</TabItem>
<TabItem value="rest" label="REST 连接">
<TabItem value="rest" label="REST connection">
对于 REST 连接,只需验证是否能成功导入 `taosrest` 模块。可在 Python 交互式 Shell 中输入:
For REST connections, verifying that the ``taosrest`'' module can be imported successfully can be done in the Python Interactive Shell by typing.
```python
import taosrest
......@@ -103,50 +103,50 @@ import taosrest
</Tabs>
:::tip
如果系统上有多个版本的 Python,则可能有多个 `pip` 命令。要确保使用的 `pip` 命令路径是正确的。上面我们用 `pip3` 命令安装,排除了使用 Python 2.x 版本对应的 `pip` 的可能性。但是如果系统上有多个 Python 3.x 版本,仍需检查安装路径是否正确。最简单的验证方式是,在命令再次输入 `pip3 install taospy`, 就会打印出 `taospy` 的具体安装位置,比如在 Windows 上:
If you have multiple versions of Python on your system, you may have various `pip` commands. Be sure to use the correct path for the `pip` command. Above, we installed the `pip3` command, which rules out the possibility of using the `pip` corresponding to Python 2.x versions. However, if you have more than one version of Python 3.x on your system, you still need to check that the installation path is correct. The easiest way to verify this is to type `pip3 install taospy` again in the command, and it will print out the exact location of `taospy`, for example, on Windows.
```
C:\> pip3 install taospy
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Requirement already satisfied: taospy in c:\users\username\appdata\local\programs\python\python310\lib\site-packages (2.3.0)
```
ðŸ™'ðŸ™'
:::
## 建立连接
## Establish connection
### 连通性测试
### Connectivity testing
在用连接器建立连接之前,建议先测试本地 TDengine CLI 到 TDengine 集群的连通性。
Before establishing a connection with the connector, we recommend testing the connectivity of the local TDengine CLI to the TDengine cluster.
<Tabs>
<TabItem value="native" label="原生连接">
<Tabs
<TabItem value="native" label="native connection">
请确保 TDengine 集群已经启动, 且集群中机器的 FQDN (如果启动的是单机版,FQDN 默认为 hostname)在本机能够解析, 可用 ping 命令进行测试:
Ensure that the TDengine cluster is up and that the FQDN of the machines in the cluster (the FQDN defaults to hostname if you are starting a standalone version) can be resolved locally, by testing with the ping command.
```
ping <FQDN>
```
然后测试用 TDengine CLI 能否正常连接集群:
Then test if the cluster can be appropriately connected with TDengine CLI: ``` ping <FQDN>```
```
taos -h <FQDN> -p <PORT>
```
上面的 FQDN 可以为集群中任意一个 dnode 的 FQDN, PORT 为这个 dnode 对应的 serverPort。
The FQDN above can be the FQDN of any dnode in the cluster, and the PORT is the serverPort corresponding to this dnode.
</TabItem>
<TabItem value="rest" label="REST 连接" groupId="connect">
</TabItem
<TabItem value="rest" label="REST connection" groupId="connect">
对于 REST 连接, 除了确保集群已经启动,还要确保 taosAdapter 组件已经启动。可以使用如下 curl 命令测试:
For REST connections and making sure the cluster is up, make sure the taosAdapter component is up. This can be tested using the following `curl ` command.
```
curl -u root:taosdata http://<FQDN>:<PORT>/rest/sql -d "select server_version()"
```
上面的 FQDN 为运行 taosAdapter 的机器的 FQDN, PORT 为 taosAdapter 配置的监听端口, 默认为 6041。
如果测试成功,会输出服务器版本信息,比如:
The FQDN above is the FQDN of the machine running taosAdapter, PORT is the port taosAdapter listening, default is 6041.
If the test is successful, it will output the server version information, e.g.
```json
{
......@@ -161,49 +161,49 @@ curl -u root:taosdata http://<FQDN>:<PORT>/rest/sql -d "select server_version()"
</TabItem>
</Tabs>
### 使用连接器建立连接
### Using connectors to establish connections
以下示例代码假设 TDengine 安装在本机, 且 FQDN 和 serverPort 都使用了默认配置。
The following example code assumes that TDengine is installed locally and that the default configuration is used for both FQDN and serverPort.
<Tabs>
<TabItem value="native" label="原生连接" groupId="connect">
<Tabs
<TabItem value="native" label="native connection" groupId="connect">
```python
{{#include docs-examples/python/connect_native_reference.py}}
```
`connect` 函数的所有参数都是可选的关键字参数。下面是连接参数的具体说明:
All arguments of the ``connect`` function are optional keyword arguments. The following are the connection parameters specified.
- `host` : 要连接的节点的 FQDN。 没有默认值。如果不同提供此参数,则会连接客户端配置文件中的 firstEP。
- `user` :TDengine 用户名。 默认值是 root。
- `password` : TDengine 用户密码。 默认值是 taosdata。
- `port` : 要连接的数据节点的起始端口,即 serverPort 配置。默认值是 6030。只有在提供了 host 参数的时候,这个参数才生效。
- `config` : 客户端配置文件路径。 在 Windows 系统上默认是 `C:\TDengine\cfg`。 在 Linux 系统上默认是 `/etc/taos/`。
- `timezone` : 查询结果中 TIMESTAMP 类型的数据,转换为 python 的 datetime 对象时使用的时区。默认为本地时区。
- `host` : The FQDN of the node to connect to. There is no default value. If this parameter is not provided, the firstEP in the client configuration file will be connected.
- `user` : The TDengine user name. The default value is `root`.
- `password` : TDengine user password. The default value is `taosdata`.
- `port` : The starting port of the data node to connect to, i.e., the serverPort configuration. The default value is 6030, which will only take effect if the host parameter is provided.
- `config` : The path to the client configuration file. On Windows systems, the default is `C:\TDengine\cfg`. The default is `/etc/taos/` on Linux systems.
- `timezone` : The timezone used to convert the TIMESTAMP data in the query results to python `datetime` objects. The default is the local timezone.
:::warning
`config` 和 `timezone` 都是进程级别的配置。建议一个进程建立的所有连接都使用相同的参数值。否则可能产生无法预知的错误。
`config` and `timezone` are both process-level configurations. we recommend that all connections made by a process use the same parameter values. Otherwise, unpredictable errors may occur.
:::
:::tip
`connect` 函数返回 `taos.TaosConnection` 实例。 在客户端多线程的场景下,推荐每个线程申请一个独立的连接实例,而不建议多线程共享一个连接。
The `connect` function returns a `taos.TaosConnection` instance. In client-side multi-threaded scenarios, we recommend that each thread request a separate connection instance rather than sharing a connection between multiple threads.
:::
</TabItem>
<TabItem value="rest" label="REST 连接">
<TabItem value="rest" label="REST connection">
```python
{{#include docs-examples/python/connect_rest_examples.py:connect}}
```
`connect` 函数的所有参数都是可选的关键字参数。下面是连接参数的具体说明:
All arguments to the `connect` function are optional keyword arguments. The following are the connection parameters specified.
- `host`: 要连接的主机。默认是 localhost。
- `user`: TDenigne 用户名。默认是 root。
- `password`: TDeingine 用户密码。默认是 taosdata。
- `port`: taosAdapter REST 服务监听端口。默认是 6041.
- `timeout`: HTTP 请求超时时间。单位为秒。默认为 `socket._GLOBAL_DEFAULT_TIMEOUT`。 一般无需配置。
- `host`: The host to connect to. The default is localhost.
- `user`: TDenigne user name. The default is `root`.
- `password`: TDeingine user password. The default is `taosdata`.
- `port`: The port on which the taosAdapter REST service listens. Default is 6041.
- `timeout`: HTTP request timeout in seconds. The default is `socket._GLOBAL_DEFAULT_TIMEOUT`. Usually, no configuration is needed.
:::note
......@@ -212,89 +212,89 @@ curl -u root:taosdata http://<FQDN>:<PORT>/rest/sql -d "select server_version()"
</TabItem>
</Tabs>
## 示例程序
## Sample program
### 基本使用
### Basic use
<Tabs default="native" groupId="connect">
<TabItem value="native" label="原生连接">
<TabItem value="native" label="native connection">
##### TaosConnection 类的使用
Use of the ##### TaosConnection class
`TaosConnection` 类既包含对 PEP249 Connection 接口的实现(如:`cursor`方法和 `close` 方法),也包含很多扩展功能(如: `execute`、 `query`、`schemaless_insert` 和 `subscribe` 方法。
The `TaosConnection` class contains both an implementation of the PEP249 Connection interface (e.g., the `cursor` method and the `close` method) and many extensions (e.g., the `execute`, `query`, `schemaless_insert`, and `subscribe` methods). .
```python title="execute 方法"
```python title="execute method"
{{#include docs-examples/python/connection_usage_native_reference.py:insert}}
```
```python title="query 方法"
```python title="query method"
{{#include docs-examples/python/connection_usage_native_reference.py:query}}
```
:::tip
查询结果只能获取一次。比如上面的示例中 `featch_all` 和 `fetch_all_into_dict` 只能用一个。重复获取得到的结果为空列表。
The queried results can only be fetched once. For example, only one of `featch_all` and `fetch_all_into_dict` can be used in the example above. Repeated fetches will result in an empty list.
:::
##### TaosResult 类的使用
##### Use of TaosResult class
上面 `TaosConnection` 类的使用示例中,我们已经展示了两种获取查询结果的方法: `featch_all` 和 `fetch_all_into_dict`。除此之外 `TaosResult` 还提供了按行迭代(`rows_iter`)或按数据块迭代(`blocks_iter`)结果集的方法。在查询数据量较大的场景,使用这两个方法会更高效。
In the above example of using the `TaosConnection` class, we have shown two ways to get the result of a query: `featch_all` and `fetch_all_into_dict`. In addition, `TaosResult` also provides methods to iterate through the result set by rows (`rows_iter`) or by data blocks (`blocks_iter`). Using these two methods will be more efficient in scenarios where the query has a large amount of data.
```python title="blocks_iter 方法"
```python title="blocks_iter method"
{{#include docs-examples/python/result_set_examples.py}}
```
##### TaosCursor 类的使用
##### Use of the TaosCursor class
`TaosConnection` 类和 `TaosResult` 类已经实现了原生接口的所有功能。如果你对 PEP249 规范中的接口比较熟悉也可以使用 `TaosCursor` 类提供的方法。
The `TaosConnection` class and the `TaosResult` class already implement all the functionality of the native interface. If you are familiar with the interfaces in the PEP249 specification, you can also use the methods provided by the `TaosCursor` class.
```python title="TaosCursor 的使用"
```python title="Use of TaosCursor"
{{#include docs-examples/python/cursor_usage_native_reference.py}}
```
:::note
TaosCursor 类使用原生连接进行写入、查询操作。在客户端多线程的场景下,这个游标实例必须保持线程独享,不能跨线程共享使用,否则会导致返回结果出现错误。
The TaosCursor class uses native connections for write and query operations. In a client-side multi-threaded scenario, this cursor instance must remain thread exclusive and cannot be shared across threads for use, otherwise, it will result in errors in the returned results.
:::
</TabItem>
<TabItem value="rest" label="REST 连接">
</TabItem
<TabItem value="rest" label="REST connection">
##### TaosRestCursor 类的使用
##### Use of TaosRestCursor class
`TaosRestCursor` 类是对 PEP249 Cursor 接口的实现。
The ``TaosRestCursor`` class is an implementation of the PEP249 Cursor interface.
```python title="TaosRestCursor 的使用"
```python title="Use of TaosRestCursor"
{{#include docs-examples/python/connect_rest_examples.py:basic}}
```
- `cursor.execute` : 用来执行任意 SQL 语句。
- `cursor.rowcount`: 对于写入操作返回写入成功记录数。对于查询操作,返回结果集行数。
- `cursor.description` : 返回字段的描述信息。关于描述信息的具体格式请参考[TaosRestCursor](https://docs.taosdata.com/api/taospy/taosrest/cursor.html)。
- `cursor.execute` : Used to execute arbitrary SQL statements.
- `cursor.rowcount` : For write operations, returns the number of successful rows written. For query operations, returns the number of rows in the result set.
- `cursor.description` : Returns the description of the field. Please refer to [TaosRestCursor](https://docs.taosdata.com/api/taospy/taosrest/cursor.html) for the specific format of the description information.
##### RestClient 类的使用
##### Use of the RestClient class
`RestClient` 类是对于 [REST API](/reference/rest-api) 的直接封装。它只包含一个 `sql()` 方法用于执行任意 SQL 语句, 并返回执行结果。
The `RestClient` class is a direct wrapper for the [REST API](/reference/rest-api). It contains only a ``sql()` method for executing arbitrary SQL statements and returning the result.
```python title="RestClient 的使用"
```python title="Use of RestClient"
{{#include docs-examples/python/rest_client_example.py}}
```
对于 `sql()` 方法更详细的介绍, 请参考 [RestClient](https://docs.taosdata.com/api/taospy/taosrest/restclient.html)。
For a more detailed description of the `sql()` method, please refer to [RestClient](https://docs.taosdata.com/api/taospy/taosrest/restclient.html).
</TabItem>
</Tabs>
### 与 pandas 一起使用
### Used with pandas
<Tabs default="native" groupId="connect">
<TabItem value="native" label="原生连接">
<TabItem value="native" label="native connection">
```python
{{#include docs-examples/python/conn_native_pandas.py}}
```
</TabItem>
<TabItem value="rest" label="REST 连接">
</TabItem
<TabItem value="rest" label="REST connection">
```python
{{#include docs-examples/python/conn_rest_pandas.py}}
......@@ -303,51 +303,50 @@ TaosCursor 类使用原生连接进行写入、查询操作。在客户端多线
</TabItem>
</Tabs>
### 其它示例程序
### Other sample programs
| 示例程序链接 | 示例程序内容 |
| ------------------------------------------------------------------------------------------------------------- | ----------------------- |
| [bind_multi.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/bind-multi.py) | 参数绑定, 一次绑定多行 |
| [bind_row.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/bind-row.py) | 参数绑定,一次绑定一行 |
| [insert_lines.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/insert-lines.py) | InfluxDB 行协议写入 |
| [json_tag.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/json-tag.py) | 使用 JSON 类型的标签 |
| [subscribe-async.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/subscribe-async.py) | 异步订阅 |
| [subscribe-sync.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/subscribe-sync.py) | 同步订阅 |
| Example program links | Example program content |
| ------------------------------------------------------------------------------------------------------------- | ------------------- ---- |
| [bind_multi.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/bind-multi.py) | parameter binding, bind multiple rows at once |
| [bind_row.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/bind-row.py) | bind_row.py
| [insert_lines.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/insert-lines.py) | InfluxDB row protocol write |
| [json_tag.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/json-tag.py) | Use JSON type tags |
| [subscribe-async.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/subscribe-async.py) | Asynchronous subscription |
| [subscribe-sync.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/subscribe-sync.py) | synchronous-subscribe |
## 其它说明
## Other notes
### 异常处理
### Exception handling
所有数据库操作如果出现异常,都会直接抛出来。由应用程序负责异常处理。比如:
All database operations will be thrown directly if an exception occurs. The application is responsible for exception handling. For example:
```python
{{#include docs-examples/python/handle_exception.py}}
```
### 关于纳秒 (nanosecond)
### About nanoseconds
由于目前 Python 对 nanosecond 支持的不完善(见下面的链接),目前的实现方式是在 nanosecond 精度时返回整数,而不是 ms 和 us 返回的 datetime 类型,应用开发者需要自行处理,建议使用 pandas 的 to_datetime()。未来如果 Python 正式完整支持了纳秒,Python 连接器可能会修改相关接口。
Due to the current imperfection of Python's nanosecond support (see link below), the current implementation returns integers at nanosecond precision instead of the `datetime` type produced by `ms and `us`, which application developers will need to handle on their own. And it is recommended to use pandas' to_datetime(). The Python Connector may modify the interface in the future if Python officially supports nanoseconds in full.
1. https://stackoverflow.com/questions/10611328/parsing-datetime-strings-containing-nanoseconds
2. https://www.python.org/dev/peps/pep-0564/
## 常见问题
## Frequently Asked Questions
欢迎[提问或报告问题](https://github.com/taosdata/taos-connector-python/issues)。
Welcome to [ask questions or report questions] (https://github.com/taosdata/taos-connector-python/issues).
## 重要更新
## Important Update
| 连接器版本 | 重要更新 | 发布日期 |
| Connector version | Important Update | Release date |
| ---------- | --------------------------------------------------------------------------------- | ---------- |
| 2.3.1 | 1. support TDengine REST API <br/> 2. remove support for Python version below 3.6 | 2022-04-28 |
| 2.2.5 | support timezone option when connect | 2022-04-13 |
| 2.2.2 | support sqlalchemy dialect plugin | 2022-03-28 |
[**Release Notes**] (https://github.com/taosdata/taos-connector-python/releases)
[**Release Notes**](https://github.com/taosdata/taos-connector-python/releases)
## API 参考
## API Reference
- [taos](https://docs.taosdata.com/api/taospy/taos/)
- [taosrest](https://docs.taosdata.com/api/taospy/taosrest)
......@@ -15,50 +15,48 @@ import RustOpenTSDBTelnet from "../../04-develop/03-insert-data/_rust_opts_telne
import RustOpenTSDBJson from "../../04-develop/03-insert-data/_rust_opts_json.mdx"
import RustQuery from "../../04-develop/04-query-data/_rust.mdx"
[![Crates.io](https://img.shields.io/crates/v/libtaos)](https://crates.io/crates/libtaos) ![Crates.io](https://img.shields.io/crates/d/libtaos) [![docs.rs](https://img.shields.io/docsrs/libtaos)](https://docs.rs/libtaos)
`libtaos` is the official Rust language connector for TDengine, through which Rust developers can develop applications that access the TDengine database.
`libtaos` 是 TDengine 的官方 Rust 语言连接器。Rust 开发人员可以通过它开发存取 TDengine 数据库的应用软件。
`libtaos` provides two ways to establish connections. One is the **Native Connection**, which connects to TDengine runtime instances via the TDengine client driver (taosc). The other is **REST connection**, which connects to TDengine runtime instances via taosAdapter's REST interface. The REST connection supports any platform, but the native connection supports all platforms on which the TDengine client can run.
`libtaos` 提供两种建立连接的方式。一种是**原生连接**,它通过 TDengine 客户端驱动程序(taosc)连接 TDengine 运行实例。另外一种是 **REST 连接**,它通过 taosAdapter 的 REST 接口连接 TDengine 运行实例。你可以通过不同的 “特性(即 Cargo 关键字 features)” 来指定使用哪种连接器。REST 连接支持任何平台,但原生连接支持所有 TDengine 客户端能运行的平台。
The source code for `libtaos` is hosted on [GitHub](https://github.com/taosdata/libtaos-rs).
`libtaos` 的源码托管在 [GitHub](https://github.com/taosdata/libtaos-rs)。
## Supported platforms
## 支持的平台
The platforms supported by native connections are the same as those supported by the TDengine client driver.
REST connections are supported on all platforms that can run Rust.
原生连接支持的平台和 TDengine 客户端驱动支持的平台一致。
REST 连接支持所有能运行 Rust 的平台。
## Version support
## 版本支持
Please refer to [version support list](/reference/connector#version support)
请参考[版本支持列表](/reference/connector#版本支持)
The Rust Connector is still under rapid development and is not guaranteed to be backward compatible before 1.0. Recommend to use TDengine version 2.4 or higher to avoid known issues.
Rust 连接器仍然在快速开发中,1.0 之前无法保证其向后兼容。建议使用 2.4 版本以上的 TDengine,以避免已知问题。
## Installation
## 安装
### Pre-installation
* Install the Rust development toolchain
* If using the native connection, please install the TDengine client driver. Please refer to [install client driver](/reference/connector#install client driver)
### 安装前准备
* 安装 Rust 开发工具链
* 如果使用原生连接,请安装 TDengine 客户端驱动,具体步骤请参考[安装客户端驱动](/reference/connector#安装客户端驱动)
### Adding libtaos dependencies
### 添加 libtaos 依赖
根据选择的连接方式,按照如下说明在 [Rust](https://rust-lang.org) 项目中添加 [libtaos][libtaos] 依赖:
Add the [libtaos][libtaos] dependency to the [Rust](https://rust-lang.org) project as follows, depending on the connection method selected.
<Tabs defaultValue="native">
<TabItem value="native" label="原生连接">
<TabItem value="native" label="native connection">
在 `Cargo.toml` 文件中添加 [libtaos][libtaos]:
Add [libtaos][libtaos] to the ``Cargo.toml`'' file.
```toml
``toml
[dependencies]
# use default feature
libtaos = "*"
```
</TabItem>
<TabItem value="rest" label="REST 连接">
</TabItem
<TabItem value="rest" label="REST connection">
在 `Cargo.toml` 文件中添加 [libtaos][libtaos],并启用 `rest` 特性。
Add [libtaos][libtaos] to the ``Cargo.toml`'' file and enable the ``rest`'' feature.
```toml
[dependencies]
......@@ -70,9 +68,9 @@ libtaos = { version = "*", features = ["rest"]}
</Tabs>
### 使用连接池
### Using connection pools
请在 `Cargo.toml` 中启用 `r2d2` 特性。
Please enable the `r2d2` feature in `Cargo.toml`.
```toml
[dependencies]
......@@ -82,9 +80,9 @@ libtaos = { version = "*", features = ["r2d2"] }
libtaos = { version = "*", features = ["rest", "r2d2"] }
```
## 建立连接
## Create a connection
[TaosCfgBuilder] 为使用者提供构造器形式的 API,以便于后续创建连接或使用连接池。
The [TaosCfgBuilder] provides the user with an API in the form of a constructor for the subsequent creation of connections or use of connection pools.
```rust
let cfg: TaosCfg = TaosCfgBuilder::default()
......@@ -98,97 +96,97 @@ let cfg: TaosCfg = TaosCfgBuilder::default()
}
```
现在您可以使用该对象创建连接:
You can now use this object to create the connection.
```rust
let conn = cfg.connect()?;
let conn = cfg.connect()? ;
```
连接对象可以创建多个:
The connection object can create more than one.
```rust
let conn = cfg.connect()?;
let conn2 = cfg.connect()?;
let conn = cfg.connect()? ;
let conn2 = cfg.connect()? ;
```
可以在应用中使用连接池:
You can use connection pools in applications.
```rust
let pool = r2d2::Pool::builder()
.max_size(10000) // max connections
.build(cfg)?;
.build(cfg)? ;
// ...
// Use pool to get connection
let conn = pool.get()?;
let conn = pool.get()? ;
```
之后您可以对数据库进行相关操作:
After that, you can perform the following operations on the database.
```rust
async fn demo() -> Result<(), Error> {
// get connection ...
// create database
conn.exec("create database if not exists demo").await?;
conn.exec("create database if not exists demo").await?
// change database context
conn.exec("use demo").await?;
conn.exec("use demo").await?
// create table
conn.exec("create table if not exists tb1 (ts timestamp, v int)").await?;
conn.exec("create table if not exists tb1 (ts timestamp, v int)").await?
// insert
conn.exec("insert into tb1 values(now, 1)").await?;
conn.exec("insert into tb1 values(now, 1)").await?
// query
let rows = conn.query("select * from tb1").await?;
let rows = conn.query("select * from tb1").await?
for row in rows.rows {
println!("{}", row.into_iter().join(","));
}
}
```
## 使用示例
## Usage examples
### 写入数据
### Write data
#### SQL 写入
#### SQL Write
<RustInsert />
#### InfluxDB 行协议写入
#### InfluxDB line protocol write
<RustInfluxLine />
#### OpenTSDB Telnet 行协议写入
#### OpenTSDB Telnet line protocol write
<RustOpenTSDBTelnet />
#### OpenTSDB JSON 行协议写入
#### OpenTSDB JSON line protocol write
<RustOpenTSDBJson />
### 查询数据
### Query data
<RustQuery />
### 更多示例程序
### More sample programs
| 程序路径 | 程序说明 |
| Program Path | Program Description |
| -------------- | ----------------------------------------------------------------------------- |
| [demo.rs] | 基本API 使用示例 |
| [bailongma-rs] | 使用 TDengine 作为存储后端的 Prometheus 远程存储 API 适配器,使用 r2d2 连接池 |
| [demo.rs] | Basic API Usage Examples |
| [bailongma-rs] | Using TDengine as the Prometheus remote storage API adapter for the storage backend, using the r2d2 connection pool |
## API 参考
## API Reference
### 连接构造器 API
### Connection constructor API
[Builder Pattern](https://doc.rust-lang.org/1.0.0/style/ownership/builders.html) 构造器模式是 Rust 处理复杂数据类型或可选配置类型的解决方案。[libtaos] 实现中,使用连接构造器 [TaosCfgBuilder] 作为 TDengine Rust 连接器的入口。[TaosCfgBuilder] 提供对服务器、端口、数据库、用户名和密码等的可选配置。
The [Builder Pattern](https://doc.rust-lang.org/1.0.0/style/ownership/builders.html) constructor pattern is Rust's solution for handling complex data types or optional configuration types. The [libtaos] implementation uses the connection constructor [TaosCfgBuilder] as the entry point for the TDengine Rust connector. The [TaosCfgBuilder] provides optional configuration of servers, ports, databases, usernames, passwords, etc.
使用 `default()` 方法可以构建一个默认参数的 [TaosCfg],用于后续连接数据库或建立连接池。
Using the ``default()` method, you can construct a [TaosCfg] with default parameters for subsequent connections to the database or establishing connection pools.
```rust
let cfg = TaosCfgBuilder::default().build()?;
let cfg = TaosCfgBuilder::default().build()? ;
```
使用构造器模式,用户可按需设置:
Using the constructor pattern, the user can set on-demand.
```rust
let cfg = TaosCfgBuilder::default()
......@@ -197,26 +195,26 @@ let cfg = TaosCfgBuilder::default()
.pass("taosdata")
.db("log")
.port(6030u16)
.build()?;
.build()? ;
```
使用 [TaosCfg] 对象创建 TDengine 连接:
Create TDengine connection using [TaosCfg] object.
```rust
let conn: Taos = cfg.connect();
```
### 连接池
### Connection pooling
在复杂应用中,建议启用连接池。[libtaos] 的连接池使用 [r2d2] 实现。
In complex applications, recommand to enable connection pooling. Connection pooling for [libtaos] is implemented using [r2d2].
如下,可以生成一个默认参数的连接池。
As follows, a connection pool with default parameters can be generated.
```rust
let pool = r2d2::Pool::new(cfg)?;
let pool = r2d2::Pool::new(cfg)? ;
```
同样可以使用连接池的构造器,对连接池参数进行设置:
You can set the same connection pool parameters using the connection pool's constructor.
```rust
use std::time::Duration;
......@@ -228,40 +226,38 @@ let pool = r2d2::Pool::new(cfg)?;
.build(cfg);
```
在应用代码中,使用 `pool.get()?` 来获取一个连接对象 [Taos]。
In the application code, use ``pool.get()? ` to get a connection object [Taos].
```rust
let taos = pool.get()?;
let taos = pool.get()? ;
```
### 连接
The [Taos] structure is the connection manager in [libtaos] and provides two main APIs.
[Taos] 结构体是 [libtaos] 中的连接管理者,主要提供了两个 API:
1. `exec`: 执行某个非查询类 SQL 语句,例如 `CREATE`,`ALTER`,`INSERT` 等。
1. ``exec``: Execute some non-query SQL statements, such as ``CREATE`, ``ALTER`, ``INSERT`, etc.
```rust
taos.exec().await?;
taos.exec().await?
```
2. `query`:执行查询语句,返回 [TaosQueryData] 对象。
2. ``query``: Execute the query statement and return the [TaosQueryData] object.
```rust
let q = taos.query("select * from log.logs").await?;
let q = taos.query("select * from log.logs").await?
```
[TaosQueryData] 对象存储了查询结果数据和返回的列的基本信息(列名,类型,长度):
The [TaosQueryData] object stores the query result data and basic information about the returned columns (column name, type, length).
列信息使用 [ColumnMeta] 存储:
Column information is stored using [ColumnMeta].
```rust
``rust
let cols = &q.column_meta;
for col in cols {
println!("name: {}, type: {:?}, bytes: {}", col.name, col.type_, col.bytes);
println!("name: {}, type: {:?} , bytes: {}", col.name, col.type_, col.bytes);
}
```
逐行获取数据:
It fetches data line by line.
```rust
for (i, row) in q.rows.iter().enumerate() {
......@@ -271,109 +267,109 @@ let taos = pool.get()?;
}
```
需要注意的是,需要使用 Rust 异步函数和异步运行时。
Note that Rust asynchronous functions and an asynchronous runtime are required.
[Taos] 提供部分 SQL 的 Rust 方法化以减少 `format!` 代码块的频率:
[Taos] provides partial Rust methodization of SQL to reduce the frequency of `format!` code blocks.
- `.describe(table: &str)`: 执行 `DESCRIBE` 并返回一个 Rust 数据结构。
- `.create_database(database: &str)`: 执行 `CREATE DATABASE` 语句。
- `.use_database(database: &str)`: 执行 `USE` 语句。
- `.describe(table: &str)`: Executes `DESCRIBE` and returns a Rust data structure.
- `.create_database(database: &str)`: Executes the `CREATE DATABASE` statement.
- `.use_database(database: &str)`: Executes the `USE` statement.
除此之外,该结构也是 [参数绑定](#参数绑定接口) 和 [行协议接口](#行协议接口) 的入口,使用方法请参考具体的 API 说明。
In addition, this structure is also the entry point for [Parameter Binding](#Parameter Binding Interface) and [Row Protocol Interface](#Row Protocol Interface). Please refer to the specific API descriptions for usage.
### 参数绑定接口
### Parameter Binding Interface
与 C 接口类似,Rust 提供参数绑定接口。首先,通过 [Taos] 对象创建一个 SQL 语句的参数绑定对象 [Stmt]:
Similar to the C interface, Rust provides a parameter binding interface. First, create a parameter binding object [Stmt] for a SQL statement from the [Taos] object.
```rust
let mut stmt: Stmt = taos.stmt("insert into ? values(?,?)")?;
let mut stmt: Stmt = taos.stmt("insert into ? values(? ,?)") ? ;
```
参数绑定对象提供了一组接口用于实现参数绑定:
The parameter binding object provides a set of interfaces for implementing parameter binding.
##### `.set_tbname(tbname: impl ToCString)`
用于绑定表名。
To bind table names.
##### `.set_tbname_tags(tbname: impl ToCString, tags: impl IntoParams)`
当 SQL 语句使用超级表时,用于绑定子表表名和标签值:
Bind sub-table table names and tag values when the SQL statement uses a super table.
```rust
let mut stmt = taos.stmt("insert into ? using stb0 tags(?) values(?,?)")?;
let mut stmt = taos.stmt("insert into ? using stb0 tags(?) values(? ,?)") ? ;
// tags can be created with any supported type, here is an example using JSON
let v = Field::Json(serde_json::from_str("{\"tag1\":\"一二三四五六七八九十\"}").unwrap());
stmt.set_tbname_tags("tb0", [&tag])?;
let v = Field::Json(serde_json::from_str("{\"tag1\":\"one, two, three, four, five, six, seven, eight, nine, ten\"}").unwrap());
stmt.set_tbname_tags("tb0", [&tag])? ;
```
##### `.bind(params: impl IntoParams)`
用于绑定值类型。使用 [Field] 结构体构建需要的类型并绑定:
Bind value types. Use the [Field] structure to construct the desired type and bind.
```rust
let ts = Field::Timestamp(Timestamp::now());
let value = Field::Float(0.0);
stmt.bind(vec![ts, value].iter())?;
stmt.bind(vec![ts, value].iter())? ;
```
##### `.execute()`
执行 SQL。[Stmt] 对象可以复用,在执行后可以重新绑定并执行。
Execute SQL.[Stmt] objects can be reused, re-binded, and executed after execution.
```rust
stmt.execute()?;
stmt.execute()? ;
// next bind cycle.
//stmt.set_tbname()?;
//stmt.bind()?;
//stmt.execute()?;
// stmt.set_tbname()? ;
//stmt.bind()? ;
//stmt.execute()? ;
```
### 行协议接口
### Row protocol interface
行协议接口支持多种模式和不同精度,需要引入 schemaless 模块中的常量以进行设置:
The line protocol interface supports multiple modes and different precision and requires the introduction of constants in the schemaless module to set.
```rust
use libtaos::*;
use libtaos::schemaless::*;
```
- InfluxDB 行协议
- InfluxDB row protocol
```rust
let lines = [
"st,t1=abc,t2=def,t3=anything c1=3i64,c3=L\"pass\",c2=false 1626006833639000000"
"st,t1=abc,t2=def,t3=anything c1=3i64,c3=L\"abc\",c4=4f64 1626006833639000000"
];
taos.schemaless_insert(&lines, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_NANOSECONDS)?;
taos.schemaless_insert(&lines, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_NANOSECONDS)? ;
```
- OpenTSDB Telnet 协议
- OpenTSDB Telnet Protocol
```rust
let lines = ["sys.if.bytes.out 1479496100 1.3E3 host=web01 interface=eth0"];
taos.schemaless_insert(&lines, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_SECONDS)?;
taos.schemaless_insert(&lines, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_SECONDS)? ;
```
- OpenTSDB JSON 协议
- OpenTSDB JSON protocol
```rust
let lines = [r#"
{
"metric": "st",
"timestamp": 1626006833,
"value": 10,
"tags": {
"t1": true,
"t2": false,
"t3": 10,
"t4": "123_abc_.!@#$%^&*:;,./?|+-=()[]{}<>"
"metric": "st",
"timestamp": 1626006833,
"value": 10,
"tags": {
"t1": true,
"t2": false,
"t3": 10,
"t4": "123_abc_.! @#$%^&*:;,. /? |+-=()[]{}<>"
}
}"#];
taos.schemaless_insert(&lines, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_SECONDS)?;
taos.schemaless_insert(&lines, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_SECONDS)? ;
```
其他相关结构体 API 使用说明请移步 Rust 文档托管网页:<https://docs.rs/libtaos>。
Please move to the Rust documentation hosting page for other related structure API usage instructions: <https://docs.rs/libtaos>.
[libtaos]: https://github.com/taosdata/libtaos-rs
[tdengine]: https://github.com/taosdata/TDengine
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册