建立连接
TDengine 提供了丰富的应用程序开发接口,为了便于用户快速开发自己的应用,TDengine 支持了多种编程语言的连接器,其中官方连接器包括支持 C/C++、Java、Python、Go、Node.js、C#、Rust、Lua(社区贡献)和 PHP (社区贡献)的连接器。这些连接器支持使用原生接口(taosc)和 REST 接口(部分语言暂不支持)连接 TDengine 集群。社区开发者也贡献了多个非官方连接器,例如 ADO.NET 连接器、Lua 连接器和 PHP 连接器。另外 TDengine 还可以直接调用 taosadapter 提供的 REST API 接口,进行数据写入和查询操作。
连接方式
连接器建立连接的方式,TDengine 提供三种:
- 通过客户端驱动程序 taosc 直接与服务端程序 taosd 建立连接,这种连接方式下文中简称 “原生连接”。
- 通过 taosAdapter 组件提供的 REST API 建立与 taosd 的连接,这种连接方式下文中简称 “REST 连接”
- 通过 taosAdapter 组件提供的 WebSocket API 建立与 taosd 的连接,这种连接方式下文中简称 “WebSocket 连接”

无论使用何种方式建立连接,连接器都提供了相同或相似的 API 操作数据库,都可以执行 SQL 语句,只是初始化连接的方式稍有不同,用户在使用上不会感到什么差别。 各种连接方式和各语言连接器支持情况请参考:连接器功能特性
关键不同点在于:
- 使用 原生连接,需要保证客户端的驱动程序 taosc 和服务端的 TDengine 版本保持一致。
- 使用 REST 连接,用户无需安装客户端驱动程序 taosc,具有跨平台易用的优势,但是无法体验数据订阅和二进制数据类型等功能。另外与 原生连接 和 WebSocket 连接相比,REST连接的性能最低。REST 接口是无状态的。在使用 REST 连接时,需要在 SQL 中指定表、超级表的数据库名称。
- 使用 WebSocket 连接,用户也无需安装客户端驱动程序 taosc。
- 连接云服务实例,必须使用 REST 连接 或 WebSocket 连接。
推荐使用 WebSocket 连接
安装客户端驱动 taosc
如果选择原生连接,而且应用程序不在 TDengine 同一台服务器上运行,你需要先安装客户端驱动,否则可以跳过此一步。为避免客户端驱动和服务端不兼容,请使用一致的版本。
安装步骤
- Linux
- Windows
-
macOS
-
下载客户端安装包
下载 TDengine

输入您的电子邮箱以接收下载链接
同意涛思数据通过此邮件地址联系我
请勾选同意,便于我们通过邮件发送安装包给您。
下载
关闭
- 解压缩软件包
将软件包放置在当前用户可读写的任意目录下,然后执行下面的命令:tar -xzvf TDengine-client-VERSION.tar.gz 其中 VERSION 需要替换为实际版本的字符串。
2. 执行安装脚本
解压软件包之后,会在解压目录下看到以下文件(目录):
- _ install_client.sh_:安装脚本,用于应用驱动程序
- _ package.tar.gz_:应用驱动安装包
- _ driver_:TDengine 应用驱动 driver
- examples: 各种编程语言的示例程序(c/C#/go/JDBC/MATLAB/python/R) 运行 install_client.sh 进行安装。
- 配置 taos.cfg
编辑 taos.cfg 文件(默认路径/etc/taos/taos.cfg),将 firstEP 修改为 TDengine 服务器的 End Point,例如:h1.tdengine.com:6030
提示
- 如本机没有部署 TDengine 服务,仅安装了应用驱动,则
taos.cfg中仅需配置firstEP,无需在本机配置FQDN。 - 为防止与服务器端连接时出现“Unable to resolve FQDN”错误,建议确认本机的
/etc/hosts文件已经配置了服务器正确的 FQDN 值,或配置好了 DNS 服务。 - 下载客户端安装包
下载 TDengine

输入您的电子邮箱以接收下载链接
同意涛思数据通过此邮件地址联系我
请勾选同意,便于我们通过邮件发送安装包给您。
下载
关闭 4. 执行安装程序,按提示选择默认值,完成安装 5. 安装路径
默认安装路径为:C:\TDengine,其中包括以下文件(目录):
- taos.exe:TDengine CLI 命令行程序
- taosadapter.exe:提供 RESTful 服务和接受其他多种软件写入请求的服务端可执行文件
- taosBenchmark.exe:TDengine 测试程序
- cfg : 配置文件目录
- driver: 应用驱动动态链接库
- examples: 示例程序 bash/C/C#/go/JDBC/Python/Node.js
- include: 头文件
- log : 日志文件
- unins000.exe: 卸载程序
- 配置 taos.cfg
编辑 taos.cfg 文件(默认路径 C:\TDengine\cfg\taos.cfg),将 firstEP 修改为 TDengine 服务器的 End Point,例如:h1.tdengine.com:6030。
提示
- 如利用 FQDN 连接服务器,必须确认本机网络环境 DNS 已配置好,或在 hosts 文件中添加 FQDN 寻址记录, 如编辑 C:\Windows\system32\drivers\etc\hosts,添加类似如下的记录:
192.168.1.99 h1.taos.com - 卸载:运行 unins000.exe 可卸载 TDengine 应用驱动。
- 下载客户端安装包
下载 TDengine

输入您的电子邮箱以接收下载链接
同意涛思数据通过此邮件地址联系我
请勾选同意,便于我们通过邮件发送安装包给您。
下载
关闭
4. 执行安装程序,按提示选择默认值,完成安装。如果安装被阻止,可以右键或者按 Ctrl 点击安装包,选择 打开。
5. 配置 taos.cfg
编辑 taos.cfg 文件(默认路径/etc/taos/taos.cfg),将 firstEP 修改为 TDengine 服务器的 End Point,例如:h1.tdengine.com:6030
提示
- 如本机没有部署 TDengine 服务,仅安装了应用驱动,则
taos.cfg中仅需配置firstEP,无需在本机配置FQDN。 - 为防止与服务器端连接时出现“Unable to resolve FQDN”错误,建议确认本机的
/etc/hosts文件已经配置了服务器正确的 FQDN 值,或配置好了 DNS 服务。
安装验证
以上安装和配置完成后,并确认 TDengine 服务已经正常启动运行,此时可以执行安装包里带有的 TDengine 命令行程序 taos 进行登录。
- Linux
- Windows
- macOS
在 Linux shell 下直接执行 taos 连接到 TDengine 服务,进入到 TDengine CLI 界面,示例如下:
1. $ taos
3. taos> show databases;
4. name |
5. =================================
6. information_schema |
7. performance_schema |
8. db |
9. Query OK, 3 rows in database (0.019154s)
11. taos>
在 cmd 下进入到 C:\TDengine 目录下直接执行 taos.exe,连接到 TDengine 服务,进入到 TDengine CLI 界面,示例如下:
1. taos> show databases;
2. name | create_time | vgroups | ntables | replica | strict | duration | keep | buffer | pagesize | pages | minrows | maxrows | comp | precision | status | retention | single_stable | cachemodel | cachesize | wal_level | wal_fsync_period | wal_retention_period | wal_retention_size |
3. ===============================================================================================================================================================================================================================================================================================================================================================================================================================
4. information_schema | NULL | NULL | 14 | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | ready | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
5. performance_schema | NULL | NULL | 3 | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | ready | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
6. test | 2022-08-04 16:46:40.506 | 2 | 0 | 1 | off | 14400m | 5256000m,5256000m,5256000m | 96 | 4 | 256 |
7. 100 | 4096 | 2 | ms | ready | NULL | false | none | 1 | 1 | 3000 | 0 | 0 | 0 | 0 |
8. Query OK, 3 rows in database (0.123000s)
10. taos>
在 macOS shell 下直接执行 taos 连接到 TDengine 服务,进入到 TDengine CLI 界面,示例如下:
1. $ taos
3. taos> show databases;
4. name |
5. =================================
6. information_schema |
7. performance_schema |
8. db |
9. Query OK, 3 rows in database (0.019154s)
11. taos>
安装连接器
- Java
- Python
- Go
- Rust
- Node.js
- C#
- C
- REST API
如果使用 Maven 管理项目,只需在 pom.xml 中加入以下依赖。
1. <dependency>
2. <groupId>com.taosdata.jdbc</groupId>
3. <artifactId>taos-jdbcdriver</artifactId>
4. <version>3.4.0</version>
5. </dependency>
-
安装前准备
-
安装 Python。新近版本 taospy 包要求 Python 3.6.2+。早期版本 taospy 包要求 Python 3.7+。taos-ws-py 包要求 Python 3.7+。如果系统上还没有 Python 可参考 Python BeginnersGuide 安装。
- 安装 pip。大部分情况下 Python 的安装包都自带了 pip 工具, 如果没有请参考 pip documentation 安装。
- 如果使用原生连接,还需安装客户端驱动。客户端软件包含了 TDengine 客户端动态链接库(libtaos.so 或 taos.dll) 和 TDengine CLI。
-
使用 pip 安装
-
卸载旧版本 如果以前安装过旧版本的 Python 连接器, 请提前卸载。
1. pip3 uninstall taos taospy 2. pip3 uninstall taos taos-ws-py- 安装taospy- 最新版本
1. pip3 install taospy- 指定某个特定版本安装1. pip3 install taospy==2.3.0- 从 GitHub 安装1. pip3 install git+https://github.com/taosdata/taos-connector-python.git
此安装包为原生连接器
- 安装 taos-ws-py1. pip3 install taos-ws-py
此安装包为 WebSocket 连接器
- 同时安装 taospy和taos-ws-py1. pip3 install taospy[ws]- 安装验证 -
原生连接
- REST 连接
- WebSocket 连接
对于原生连接,需要验证客户端驱动和 Python 连接器本身是否都正确安装。如果能成功导入 taos 模块,则说明已经正确安装了客户端驱动和 Python 连接器。可在 Python 交互式 Shell 中输入:
1. import taos
对于 REST 连接,只需验证是否能成功导入 taosrest 模块。可在 Python 交互式 Shell 中输入:
1. import taosrest
对于 WebSocket 连接,只需验证是否能成功导入 taosws 模块。可在 Python 交互式 Shell 中输入:
1. import taosws
编辑 go.mod 添加 driver-go 依赖即可。
1. module goexample
3. go 1.17
5. require github.com/taosdata/driver-go/v3 latest
备注
driver-go 使用 cgo 封装了 taosc 的 API。cgo 需要使用 GCC 编译 C 的源码。因此需要确保你的系统上有 GCC。
编辑 Cargo.toml 添加 taos 依赖即可。
1. [dependencies]
2. taos = { version = "*"}
信息
Rust 连接器通过不同的特性区分不同的连接方式。默认同时支持原生连接和 WebSocket 连接,如果仅需要建立 WebSocket 连接,可设置 ws 特性:
1. taos = { version = "*", default-features = false, features = ["ws"] }
-
安装前准备
-
安装 Node.js 开发环境, 使用14以上版本。下载链接: <https://nodejs.org/en/download/>
-
安装
-
使用 npm 安装 Node.js 连接器
1. npm install @tdengine/websocket
Node.js 目前只支持 WebSocket 连接
- 安装验证
- 新建安装验证目录,例如:
~/tdengine-test,下载 GitHub 上 nodejsChecker.js 源代码到本地。 -
在命令行中执行以下命令。
1. npm init -y 2. npm install @tdengine/websocket 3. node nodejsChecker.js- 执行以上步骤后,在命令行会输出 nodeChecker.js 连接 TDengine 实例,并执行简单插入和查询的结果。
编辑项目配置文件中添加 TDengine.Connector 的引用即可:
1. <Project Sdk="Microsoft.NET.Sdk">
3. <PropertyGroup>
4. <OutputType>Exe</OutputType>
5. <TargetFramework>net6.0</TargetFramework>
6. <ImplicitUsings>enable</ImplicitUsings>
7. <Nullable>enable</Nullable>
8. <StartupObject>TDengineExample.AsyncQueryExample</StartupObject>
9. </PropertyGroup>
11. <ItemGroup>
12. <PackageReference Include="TDengine.Connector" Version="3.1.0" />
13. </ItemGroup>
15. </Project>
也可通过 dotnet 命令添加:
1. dotnet add package TDengine.Connector
备注
以下示例代码,均基于 dotnet6.0,如果使用其它版本,可能需要做适当调整。
如果已经安装了 TDengine 服务端软件或 TDengine 客户端驱动 taosc, 那么已经安装了 C 连接器,无需额外操作。
使用 REST API 方式访问 TDengine,无需安装任何驱动和连接器。
建立连接
在执行这一步之前,请确保有一个正在运行的,且可以访问到的 TDengine,而且服务端的 FQDN 配置正确。以下示例代码,都假设 TDengine 安装在本机,且 FQDN(默认 localhost) 和 serverPort(默认 6030) 都使用默认配置。
连接参数
连接的配置项较多,因此在建立连接之前,我们能先介绍一下各语言连接器建立连接使用的参数。
- Java
- Python
- Go
- Rust
- Node.js
- C#
- C
- REST API
Java 连接器建立连接的参数有 URL 和 Properties。
TDengine 的 JDBC URL 规范格式为: jdbc:[TAOS|TAOS-WS|TAOS-RS]://[host_name]:[port]/[database_name]?[user={user}|&password={password}|&charset={charset}|&cfgdir={config_dir}|&locale={locale}|&timezone={timezone}|&batchfetch={batchfetch}]
URL 和 Properties 的详细参数说明和如何使用详见 url 规范
Python 连接器使用 connect() 方法来建立连接,下面是连接参数的具体说明:
- url:
taosAdapterREST 服务的 URL。默认是localhost的6041端口。 - user: TDengine 用户名。默认是
root。 - password: TDengine 用户密码。默认是
taosdata。 - timeout: HTTP 请求超时时间。单位为秒。默认为
socket._GLOBAL_DEFAULT_TIMEOUT。一般无需配置。
数据源名称具有通用格式,例如 PEAR DB,但没有类型前缀(方括号表示可选):
1. [username[:password]@][protocol[(address)]]/[dbname][?param1=value1&...¶mN=valueN]
完整形式的 DSN:
1. username:password@protocol(address)/dbname?param=value
支持的 DSN 参数如下
原生连接:
cfg指定 taos.cfg 目录cgoThread指定 cgo 同时执行的数量,默认为系统核数cgoAsyncHandlerPoolSize指定异步函数的 handle 大小,默认为 10000
REST 连接:
disableCompression是否接受压缩数据,默认为 true 不接受压缩数据,如果传输数据使用 gzip 压缩设置为 false。readBufferSize读取数据的缓存区大小默认为 4K(4096),当查询结果数据量多时可以适当调大该值。token连接云服务时使用的 token。skipVerify是否跳过证书验证,默认为 false 不跳过证书验证,如果连接的是不安全的服务设置为 true。
WebSocket 连接:
enableCompression是否发送压缩数据,默认为 false 不发送压缩数据,如果传输数据使用压缩设置为 true。readTimeout读取数据的超时时间,默认为 5m。writeTimeout写入数据的超时时间,默认为 10s。
Rust 连接器使用 DSN 来创建连接, DSN 描述字符串基本结构如下:
1. <driver>[+<protocol>]://[[<username>:<password>@]<host>:<port>][/<database>][?<p1>=<v1>[&<p2>=<v2>]]
2. |------|------------|---|-----------|-----------|------|------|------------|-----------------------|
3. |driver| protocol | | username | password | host | port | database | params |
DSN 的详细说明和如何使用详见 连接功能
Node.js 连接器使用 DSN 来创建连接, DSN 描述字符串基本结构如下:
1. [+<protocol>]://[[<username>:<password>@]<host>:<port>][/<database>][?<p1>=<v1>[&<p2>=<v2>]]
2. |------------|---|-----------|-----------|------|------|------------|-----------------------|
3. | protocol | | username | password | host | port | database | params |
- protocol: 使用 websocket 协议建立连接。例如
ws://localhost:6041 - username/password: 数据库的用户名和密码。
- host/port: 主机地址和端口号。例如
localhost:6041 - database: 数据库名称。
- params: 其他参数。 例如token。
- 完整 DSN 示例:
1. ws://root:taosdata@localhost:6041
ConnectionStringBuilder 使用 key-value 对方式设置连接参数,key 为参数名,value 为参数值,不同参数之间使用分号 ; 分割。
例如:
1. "protocol=WebSocket;host=127.0.0.1;port=6041;useSSL=false"
支持的参数如下:
host:TDengine 运行实例的地址。port:TDengine 运行实例的端口。username:连接的用户名。password:连接的密码。protocol:连接的协议,可选值为 Native 或 WebSocket,默认为 Native。db:连接的数据库。timezone:时区,默认为本地时区。connTimeout:连接超时时间,默认为 1 分钟。
WebSocket 连接额外支持以下参数:
readTimeout:读取超时时间,默认为 5 分钟。writeTimeout:发送超时时间,默认为 10 秒。token:连接 TDengine cloud 的 token。useSSL:是否使用 SSL 连接,默认为 false。enableCompression:是否启用 WebSocket 压缩,默认为 false。autoReconnect:是否自动重连,默认为 false。reconnectRetryCount:重连次数,默认为 3。reconnectIntervalMs:重连间隔毫秒时间,默认为 2000。
WebSocket 连接
C/C++ 语言连接器 WebSocket 连接方式使用 ws_connect() 函数用于建立与 TDengine 数据库的连接。其参数为 DSN 描述字符串,其基本结构如下:
1. <driver>[+<protocol>]://[[<username>:<password>@]<host>:<port>][/<database>][?<p1>=<v1>[&<p2>=<v2>]]
2. |------|------------|---|-----------|-----------|------|------|------------|-----------------------|
3. |driver| protocol | | username | password | host | port | database | params |
DSN 的详细说明和如何使用详见 连接功能
原生连接
C/C++ 语言连接器原生连接方式使用 taos_connect() 函数用于建立与 TDengine 数据库的连接。其参数详细说明如下:
host:要连接的数据库服务器的主机名或IP地址。如果是本地数据库,可以使用"localhost"。user:用于登录数据库的用户名。passwd:与用户名对应的密码。db:连接时默认选择的数据库名。如果不指定数据库,可以传递NULL或空字符串。port:数据库服务器监听的端口号。默认的端口号是6030。
还提供了 taos_connect_auth() 函数用于使用 MD5 加密的密码建立与 TDengine 数据库的连接。此函数与 taos_connect 功能相同,不同之处在于密码的处理方式,taos_connect_auth 需要的是密码的 MD5 加密字符串。
通过 REST API 方式访问 TDengine 时,应用程序直接与 taosAdapter 建立 HTTP 连接,建议使用连接池来管理连接。 使用 REST API 的参数具体可以参考:http-请求格式
WebSocket 连接
下面是各语言连接器建立 WebSocket 连接代码样例。演示了如何使用 WebSocket 连接方式连接到 TDengine 数据库,并对连接设定一些参数。整个过程主要涉及到数据库连接的建立和异常处理。
- Java
- Python
- Go
- Rust
- Node.js
- C#
- C
- REST API
1. public static void main(String[] args) throws Exception {
2. // use
3. // String jdbcUrl =
4. // "jdbc:TAOS-WS://localhost:6041/dbName?user=root&password=taosdata";
5. // if you want to connect a specified database named "dbName".
6. String jdbcUrl = "jdbc:TAOS-WS://localhost:6041?user=root&password=taosdata";
7. Properties connProps = new Properties();
8. connProps.setProperty(TSDBDriver.PROPERTY_KEY_ENABLE_AUTO_RECONNECT, "true");
9. connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
10. connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
12. try (Connection conn = DriverManager.getConnection(jdbcUrl, connProps)) {
13. System.out.println("Connected to " + jdbcUrl + " successfully.");
15. // you can use the connection for execute SQL here
17. } catch (Exception ex) {
18. // please refer to the JDBC specifications for detailed exceptions info
19. System.out.printf("Failed to connect to %s, %sErrMessage: %s%n",
20. jdbcUrl,
21. ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "",
22. ex.getMessage());
23. // Print stack trace for context in examples. Use logging in production.
24. ex.printStackTrace();
25. throw ex;
26. }
27. }
1. import taosws
3. def create_connection():
4. conn = None
5. host = "localhost"
6. port = 6041
7. try:
8. conn = taosws.connect(
9. user="root",
10. password="taosdata",
11. host=host,
12. port=port,
13. )
14. print(f"Connected to {host}:{port} successfully.");
15. except Exception as err:
16. print(f"Failed to connect to {host}:{port} , ErrMessage:{err}")
17. raise err
18. return conn
1. package main
3. import (
4. "database/sql"
5. "fmt"
6. "log"
8. _ "github.com/taosdata/driver-go/v3/taosWS"
9. )
11. func main() {
12. // use
13. // var taosDSN = "root:taosdata@ws(localhost:6041)/dbName"
14. // if you want to connect a specified database named "dbName".
15. var taosDSN = "root:taosdata@ws(localhost:6041)/"
16. taos, err := sql.Open("taosWS", taosDSN)
17. if err != nil {
18. log.Fatalln("Failed to connect to " + taosDSN + "; ErrMessage: " + err.Error())
19. }
20. fmt.Println("Connected to " + taosDSN + " successfully.")
21. defer taos.Close()
22. }
1. use taos::*;
3. #[tokio::main]
4. async fn main() -> anyhow::Result<()> {
5. let dsn = "ws://localhost:6041".to_string();
7. match TaosBuilder::from_dsn(&dsn)?.build().await {
8. Ok(_taos) => {
9. println!("Connected to {} successfully.", dsn);
10. Ok(())
11. }
12. Err(err) => {
13. eprintln!("Failed to connect to {}, ErrMessage: {}", dsn, err);
14. return Err(err.into());
15. }
16. }
17. }
1. const taos = require("@tdengine/websocket");
3. let dsn = 'ws://localhost:6041';
4. async function createConnect() {
5. try {
6. let conf = new taos.WSConfig(dsn);
7. conf.setUser('root');
8. conf.setPwd('taosdata');
9. conf.setDb('power');
10. conn = await taos.sqlConnect(conf);
11. console.log("Connected to " + dsn + " successfully.");
12. return conn;
13. } catch (err) {
14. console.log("Failed to connect to " + dsn + ", ErrCode: " + err.code + ", ErrMessage: " + err.message);
15. throw err;
16. }
18. }
1. static void Main(string[] args)
2. {
3. var connectionString =
4. "protocol=WebSocket;host=localhost;port=6041;useSSL=false;username=root;password=taosdata";
5. try
6. {
7. // Connect to TDengine server using WebSocket
8. var builder = new ConnectionStringBuilder(connectionString);
9. // Open connection with using block, it will close the connection automatically
10. using (var client = DbDriver.Open(builder))
11. {
12. Console.WriteLine("Connected to " + connectionString + " successfully.");
13. }
14. }
15. catch (TDengineError e)
16. {
17. // handle TDengine error
18. Console.WriteLine("Failed to connect to " + connectionString + "; ErrCode:" + e.Code +
19. "; ErrMessage: " + e.Error);
20. throw;
21. }
22. catch (Exception e)
23. {
24. // handle other exceptions
25. Console.WriteLine("Failed to connect to " + connectionString + "; Err:" + e.Message);
26. throw;
27. }
28. }
1. // compile with
2. // gcc connect_example.c -o connect_example -ltaos
3. #include <stdio.h>
4. #include <stdlib.h>
5. #include "taosws.h"
7. int main() {
8. ws_enable_log("debug");
9. char *dsn = "ws://localhost:6041";
10. WS_TAOS *taos = ws_connect(dsn);
11. if (taos == NULL) {
12. fprintf(stderr, "Failed to connect to %s, ErrCode: 0x%x, ErrMessage: %s.\n", dsn, ws_errno(NULL), ws_errstr(NULL));
13. return -1;
14. }
15. fprintf(stdout, "Connected to %s successfully.\n", dsn);
17. /* put your code here for read and write */
19. // close & clean
20. ws_close(taos);
21. }
不支持
原生连接
下面是各语言连接器建立原生连接代码样例。演示了如何使用原生连接方式连接到 TDengine 数据库,并对连接设定一些参数。整个过程主要涉及到数据库连接的建立和异常处理。
- Java
- Python
- Go
- Rust
- Node.js
- C#
- C
- REST API
1. public static void main(String[] args) throws Exception {
2. // use
3. // String jdbcUrl =
4. // "jdbc:TAOS://localhost:6030/dbName?user=root&password=taosdata";
5. // if you want to connect a specified database named "dbName".
6. String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata";
7. Properties connProps = new Properties();
8. connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
9. connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
10. connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
12. try (Connection conn = DriverManager.getConnection(jdbcUrl, connProps)) {
13. System.out.println("Connected to " + jdbcUrl + " successfully.");
15. // you can use the connection for execute SQL here
17. } catch (Exception ex) {
18. // please refer to the JDBC specifications for detailed exceptions info
19. System.out.printf("Failed to connect to %s, %sErrMessage: %s%n",
20. jdbcUrl,
21. ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "",
22. ex.getMessage());
23. // Print stack trace for context in examples. Use logging in production.
24. ex.printStackTrace();
25. throw ex;
26. }
27. }
1. import taos
3. def create_connection():
4. # all parameters are optional.
5. conn = None
6. host = "localhost"
7. port = 6030
8. try:
9. conn = taos.connect(
10. user="root",
11. password="taosdata",
12. host=host,
13. port=port,
14. )
15. print(f"Connected to {host}:{port} successfully.");
16. except Exception as err:
17. print(f"Failed to connect to {host}:{port} , ErrMessage:{err}")
18. raise err
19. finally:
20. if conn:
21. conn.close()
24. if __name__ == "__main__":
25. create_connection()
1. package main
3. import (
4. "database/sql"
5. "fmt"
6. "log"
8. _ "github.com/taosdata/driver-go/v3/taosSql"
9. )
11. func main() {
12. // use
13. // var taosDSN = "root:taosdata@tcp(localhost:6030)/dbName"
14. // if you want to connect a specified database named "dbName".
15. var taosDSN = "root:taosdata@tcp(localhost:6030)/"
16. taos, err := sql.Open("taosSql", taosDSN)
17. if err != nil {
18. log.Fatalln("Failed to connect to " + taosDSN + "; ErrMessage: " + err.Error())
19. }
20. fmt.Println("Connected to " + taosDSN + " successfully.")
21. defer taos.Close()
22. }
1. use taos::*;
3. #[tokio::main]
4. async fn main() -> anyhow::Result<()> {
5. let dsn = "taos://localhost:6030".to_string();
7. match TaosBuilder::from_dsn(&dsn)?.build().await {
8. Ok(_taos) => {
9. println!("Connected to {} successfully.", dsn);
10. Ok(())
11. }
12. Err(err) => {
13. eprintln!("Failed to connect to {}, ErrMessage: {}", dsn, err);
14. return Err(err.into());
15. }
16. }
17. }
不支持
1. static void Main(String[] args)
2. {
3. var connectionString = "host=127.0.0.1;port=6030;username=root;password=taosdata";
4. try
5. {
6. // Connect to TDengine server using Native
7. var builder = new ConnectionStringBuilder(connectionString);
8. // Open connection with using block, it will close the connection automatically
9. using (var client = DbDriver.Open(builder))
10. {
11. Console.WriteLine("Connected to " + connectionString + " successfully.");
12. }
13. }
14. catch (TDengineError e)
15. {
16. // handle TDengine error
17. Console.WriteLine("Failed to connect to " + connectionString + "; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
18. throw;
19. }
20. catch (Exception e)
21. {
22. // handle other exceptions
23. Console.WriteLine("Failed to connect to " + connectionString + "; Err:" + e.Message);
24. throw;
25. }
26. }
1. // compile with
2. // gcc connect_example.c -o connect_example -ltaos
3. #include <stdio.h>
4. #include <stdlib.h>
5. #include "taos.h"
7. int main() {
8. const char *host = "localhost";
9. const char *user = "root";
10. const char *passwd = "taosdata";
11. const char *db = NULL; // if don't want to connect to a default db, set it to NULL or ""
12. uint16_t port = 6030; // 0 means use the default port
13. TAOS *taos = taos_connect(host, user, passwd, db, port);
14. if (taos == NULL) {
15. fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL));
16. taos_cleanup();
17. return -1;
18. }
19. fprintf(stdout, "Connected to %s:%hu successfully.\n", host, port);
21. /* put your code here for read and write */
23. // close & clean
24. taos_close(taos);
25. taos_cleanup();
26. }
不支持
REST 连接
下面是各语言连接器建立 REST 连接代码样例。演示了如何使用 REST 连接方式连接到 TDengine 数据库。整个过程主要涉及到数据库连接的建立和异常处理。
- Java
- Python
- Go
- Rust
- Node.js
- C#
- C
- REST API
1. public static void main(String[] args) throws Exception {
2. String jdbcUrl = "jdbc:TAOS-RS://localhost:6041?user=root&password=taosdata";
3. try (Connection conn = DriverManager.getConnection(jdbcUrl)) {
4. System.out.println("Connected to " + jdbcUrl + " successfully.");
6. // you can use the connection for execute SQL here
8. } catch (Exception ex) {
9. // please refer to the JDBC specifications for detailed exceptions info
10. System.out.printf("Failed to connect to %s, %sErrMessage: %s%n",
11. jdbcUrl,
12. ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "",
13. ex.getMessage());
14. // Print stack trace for context in examples. Use logging in production.
15. ex.printStackTrace();
16. throw ex;
17. }
18. }
1. import taosrest
3. def create_connection():
4. conn = None
5. url="http://localhost:6041"
6. try:
7. conn = taosrest.connect(url=url,
8. user="root",
9. password="taosdata",
10. timeout=30)
12. print(f"Connected to {url} successfully.");
13. except Exception as err:
14. print(f"Failed to connect to {url} , ErrMessage:{err}")
15. finally:
16. if conn:
17. conn.close()
1. package main
3. import (
4. "database/sql"
5. "fmt"
6. "log"
8. _ "github.com/taosdata/driver-go/v3/taosRestful"
9. )
11. func main() {
12. // use
13. // var taosDSN = "root:taosdata@http(localhost:6041)/dbName"
14. // if you want to connect a specified database named "dbName".
15. var taosDSN = "root:taosdata@http(localhost:6041)/"
16. taos, err := sql.Open("taosRestful", taosDSN)
17. if err != nil {
18. log.Fatalln("Failed to connect to " + taosDSN + "; ErrMessage: " + err.Error())
19. }
20. fmt.Println("Connected to " + taosDSN + " successfully.")
21. defer taos.Close()
22. }
不支持
不支持
不支持
不支持
使用 REST API 方式访问 TDengine,由应用程序自主去建立 HTTP 连接。
提示
如果建立连接失败,大部分情况下是 FQDN 或防火墙的配置不正确,详细的排查方法请看《常见问题及反馈》中的“遇到错误 Unable to establish connection, 我怎么办?”
连接池
有些连接器提供了连接池,或者可以与已有的连接池组件配合使用。 使用连接池,应用程序可以快速地从连接池中获取可用连接,避免了每次操作时创建和销毁连接的开销。这不仅减少了资源消耗,还提高了响应速度。此外,连接池还支持对连接的管理,如最大连接数限制、连接的有效性检查,确保了连接的高效和可靠使用。我们推荐使用连接池管理连接。 下面是各语言连接器的连接池支持代码样例。
- Java
- Python
- Go
- Rust
HikariCP
使用示例如下:
1. public static void main(String[] args) throws Exception {
2. HikariConfig config = new HikariConfig();
3. // jdbc properties
4. config.setJdbcUrl("jdbc:TAOS://127.0.0.1:6030/log");
5. config.setUsername("root");
6. config.setPassword("taosdata");
7. // connection pool configurations
8. config.setMinimumIdle(10); // minimum number of idle connection
9. config.setMaximumPoolSize(10); // maximum number of connection in the pool
10. config.setConnectionTimeout(30000); // maximum wait milliseconds for get connection from pool
11. config.setMaxLifetime(0); // maximum life time for each connection
12. config.setIdleTimeout(0); // max idle time for recycle idle connection
13. config.setConnectionTestQuery("SELECT SERVER_VERSION()"); // validation query
15. HikariDataSource dataSource = new HikariDataSource(config); // create datasource
17. Connection connection = dataSource.getConnection(); // get connection
18. Statement statement = connection.createStatement(); // get statement
20. // query or insert
21. // ...
22. statement.close();
23. connection.close(); // put back to connection pool
24. dataSource.close();
25. }
通过 HikariDataSource.getConnection() 获取连接后,使用完成后需要调用 close() 方法,实际上它并不会关闭连接,只是放回连接池中。 更多 HikariCP 使用问题请查看官方说明。
Druid
使用示例如下:
1. public static void main(String[] args) throws Exception {
2. String url = "jdbc:TAOS://127.0.0.1:6030/log";
4. DruidDataSource dataSource = new DruidDataSource();
5. // jdbc properties
6. dataSource.setDriverClassName("com.taosdata.jdbc.TSDBDriver");
7. dataSource.setUrl(url);
8. dataSource.setUsername("root");
9. dataSource.setPassword("taosdata");
10. // pool configurations
11. dataSource.setInitialSize(10);
12. dataSource.setMinIdle(10);
13. dataSource.setMaxActive(10);
14. dataSource.setMaxWait(30000);
15. dataSource.setValidationQuery("SELECT SERVER_VERSION()");
17. Connection connection = dataSource.getConnection(); // get connection
18. Statement statement = connection.createStatement(); // get statement
19. // query or insert
20. // ...
22. statement.close();
23. connection.close(); // put back to connection pool
24. dataSource.close();
25. }
更多 druid 使用问题请查看官方说明。
1. import taos
3. def create_connection():
4. # all parameters are optional.
5. conn = None
6. host = "localhost"
7. port = 6030
8. try:
9. conn = taos.connect(
10. user="root",
11. password="taosdata",
12. host=host,
13. port=port,
14. )
15. print(f"Connected to {host}:{port} successfully.");
16. except Exception as err:
17. print(f"Failed to connect to {host}:{port} , ErrMessage:{err}")
18. raise err
19. finally:
20. if conn:
21. conn.close()
24. if __name__ == "__main__":
25. create_connection()
使用 sql.Open 创建出来的连接已经实现了连接池,可以通过 API 设置连接池参数,样例如下
1. // SetMaxOpenConns sets the maximum number of open connections to the database. 0 means unlimited.
2. taos.SetMaxOpenConns(0)
3. // SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
4. taos.SetMaxIdleConns(2)
5. // SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
6. taos.SetConnMaxLifetime(0)
7. // SetConnMaxIdleTime sets the maximum amount of time a connection may be idle.
8. taos.SetConnMaxIdleTime(0)
在复杂应用中,建议启用连接池。[taos] 的连接池默认(异步模式)使用 [deadpool] 实现。
如下,可以生成一个默认参数的连接池。
1. let pool: Pool<TaosBuilder> = TaosBuilder::from_dsn("taos:///")
2. .unwrap()
3. .pool()
4. .unwrap();
同样可以使用连接池的构造器,对连接池参数进行设置:
1. let pool: Pool<TaosBuilder> = Pool::builder(Manager::from_dsn(self.dsn.clone()).unwrap().0)
2. .max_size(88) // 最大连接数
3. .build()
4. .unwrap();
在应用代码中,使用 pool.get()? 来获取一个连接对象 [Taos]。
1. let taos = pool.get()?;
