建立连接

TDengine 提供了丰富的应用程序开发接口,为了便于用户快速开发自己的应用,TDengine 支持了多种编程语言的连接器,其中官方连接器包括支持 C/C++、Java、Python、Go、Node.js、C#、Rust、Lua(社区贡献)和 PHP (社区贡献)的连接器。这些连接器支持使用原生接口(taosc)和 REST 接口(部分语言暂不支持)连接 TDengine 集群。社区开发者也贡献了多个非官方连接器,例如 ADO.NET 连接器、Lua 连接器和 PHP 连接器。

连接器建立连接的方式

连接器建立连接的方式,TDengine 提供两种:

  1. 通过 taosAdapter 组件提供的 REST API 建立与 taosd 的连接,这种连接方式下文中简称“REST 连接”
  2. 通过客户端驱动程序 taosc 直接与服务端程序 taosd 建立连接,这种连接方式下文中简称“原生连接”。

无论使用何种方式建立连接,连接器都提供了相同或相似的 API 操作数据库,都可以执行 SQL 语句,只是初始化连接的方式稍有不同,用户在使用上不会感到什么差别。

关键不同点在于:

  1. 使用 REST 连接,用户无需安装客户端驱动程序 taosc,具有跨平台易用的优势,但性能要下降 30% 左右。
  2. 使用原生连接可以体验 TDengine 的全部功能,如参数绑定接口、订阅等等。

安装客户端驱动 taosc

如果选择原生连接,而且应用程序不在 TDengine 同一台服务器上运行,你需要先安装客户端驱动,否则可以跳过此一步。为避免客户端驱动和服务端不兼容,请使用一致的版本。

安装步骤

  • Linux
  • Windows
  • macOS

  • 下载客户端安装包

下载 TDengine

TDengine Database

输入您的电子邮箱以接收下载链接

同意涛思数据通过此邮件地址联系我

请勾选同意,便于我 们通过邮件发送安装包给您。

下载

关闭

所有下载 2. 解压缩软件包

将软件包放置在当前用户可读写的任意目录下,然后执行下面的命令:tar -xzvf TDengine-client-VERSION.tar.gz 其中 VERSION 需要替换为实际版本的字符串。 3. 执行安装脚本

解压软件包之后,会在解压目录下看到以下文件(目录):

  • install_client.sh:安装脚本,用于应用驱动程序
  • taos.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

建立连接 - 图2tip
  1. 如本机没有部署 TDengine 服务,仅安装了应用驱动,则 taos.cfg 中仅需配置 firstEP,无需在本机配置 FQDN。
  2. 为防止与服务器端连接时出现“Unable to resolve FQDN”错误,建议确认本机的 /etc/hosts 文件已经配置了服务器正确的 FQDN 值,或配置好了 DNS 服务。
  3. 下载客户端安装包

下载 TDengine

TDengine Database

输入您的电子邮箱以接收下载链接

同意涛思数据通过此邮件地址联系我

请勾选同意,便于我 们通过邮件发送安装包给您。

下载

关闭

所有下载 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。

建立连接 - 图4tip
  1. 如利用 FQDN 连接服务器,必须确认本机网络环境 DNS 已配置好,或在 hosts 文件中添加 FQDN 寻址记录, 如编辑 C:\Windows\system32\drivers\etc\hosts,添加类似如下的记录:192.168.1.99 h1.taos.com
  2. 卸载:运行 unins000.exe 可卸载 TDengine 应用驱动。
  3. 下载客户端安装包

下载 TDengine

TDengine Database

输入您的电子邮箱以接收下载链接

同意涛思数据通过此邮件地址联系我

请勾选同意,便于我 们通过邮件发送安装包给您。

下载

关闭

所有下载 4. 执行安装程序,按提示选择默认值,完成安装。如果安装被阻止,可以右键或者按 Ctrl 点击安装包,选择 打开。 5. 配置 taos.cfg

编辑 taos.cfg 文件(默认路径/etc/taos/taos.cfg),将 firstEP 修改为 TDengine 服务器的 End Point,例如:h1.tdengine.com:6030

建立连接 - 图6tip
  1. 如本机没有部署 TDengine 服务,仅安装了应用驱动,则 taos.cfg 中仅需配置 firstEP,无需在本机配置 FQDN。
  2. 为防止与服务器端连接时出现“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   | wal_roll_period |     wal_seg_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 |            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 |            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#
  • R
  • C
  • PHP

如果使用 Maven 管理项目,只需在 pom.xml 中加入以下依赖。

1. <dependency>
2. <groupId>com.taosdata.jdbc</groupId>
3. <artifactId>taos-jdbcdriver</artifactId>
4. <version>3.0.0</version>
5. </dependency>

使用 pip 从 PyPI 安装:

1. pip install taospy

从 Git URL 安装:

1. pip install git+https://github.com/taosdata/taos-connector-python.git

编辑 go.mod 添加 driver-go 依赖即可。

go.mod

1. module goexample

3. go 1.17

5. require github.com/taosdata/driver-go/v3 latest
建立连接 - 图7note

driver-go 使用 cgo 封装了 taosc 的 API。cgo 需要使用 GCC 编译 C 的源码。因此需要确保你的系统上有 GCC。

编辑 Cargo.toml 添加 libtaos 依赖即可。

Cargo.toml

1. [dependencies]
2. libtaos = { version = "0.4.2"}
建立连接 - 图8info

Rust 连接器通过不同的特性区分不同的连接方式。如果要建立 REST 连接,需要开启 rest 特性:

1. libtaos = { version = "*", features = ["rest"] }

Node.js 连接器通过不同的包提供不同的连接方式。

  1. 安装 Node.js 原生连接器
1. npm install @tdengine/client
建立连接 - 图9note

推荐 Node 版本大于等于 node-v12.8.0 小于 node-v13.0.0

  1. 安装 Node.js REST 连接器
1. npm install @tdengine/rest

编辑项目配置文件中添加 TDengine.Connector 的引用即可:

csharp.csproj

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.0.0" />
13. </ItemGroup>

15. </Project>

也可通过 dotnet 命令添加:

1. dotnet add package TDengine.Connector
建立连接 - 图10note

以下示例代码,均基于 dotnet6.0,如果使用其它版本,可能需要做适当调整。

  1. 下载 taos-jdbcdriver-version-dist.jar。
  2. 安装 R 的依赖包RJDBC:
1. install.packages("RJDBC")

如果已经安装了 TDengine 服务端软件或 TDengine 客户端驱动 taosc, 那么已经安装了 C 连接器,无需额外操作。

下载代码并解压:

1. curl -L -o php-tdengine.tar.gz https://github.com/Yurunsoft/php-tdengine/archive/refs/tags/v1.0.2.tar.gz \
2. && mkdir php-tdengine \
3. && tar -xzf php-tdengine.tar.gz -C php-tdengine --strip-components=1

版本 v1.0.2 只是示例,可替换为任意更新的版本,可在 TDengine PHP Connector 发布历史 中查看可用版本。

非 Swoole 环境:

1. phpize && ./configure && make -j && make install

手动指定 TDengine 目录:

1. phpize && ./configure --with-tdengine-dir=/usr/local/Cellar/tdengine/3.0.0.0 && make -j && make install

--with-tdengine-dir= 后跟上 TDengine 目录。 适用于默认找不到的情况,或者 macOS 系统用户。

Swoole 环境:

1. phpize && ./configure --enable-swoole && make -j && make install

启用扩展:

方法一:在 php.ini 中加入 extension=tdengine

方法二:运行带参数 php -d extension=tdengine test.php

建立连接

在执行这一步之前,请确保有一个正在运行的,且可以访问到的 TDengine,而且服务端的 FQDN 配置正确。以下示例代码,都假设 TDengine 安装在本机,且 FQDN(默认 localhost) 和 serverPort(默认 6030) 都使用默认配置。

  • Java
  • Python
  • Go
  • Rust
  • Node.js
  • C#
  • R
  • C
  • PHP

原生连接

1. package com.taos.example;

3. import java.sql.Connection;
4. import java.sql.DriverManager;
5. import java.sql.SQLException;
6. import java.util.Properties;

8. import com.taosdata.jdbc.TSDBDriver;

10. public class JNIConnectExample {
11. public static void main(String[] args) throws SQLException {
12. String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata";
13. Properties connProps = new Properties();
14. connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
15. connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
16. connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
17. Connection conn = DriverManager.getConnection(jdbcUrl, connProps);
18. System.out.println("Connected");
19. conn.close();
20. }
21. }

23. // use
24. // String jdbcUrl = "jdbc:TAOS://localhost:6030/dbName?user=root&password=taosdata";
25. // if you want to connect a specified database named "dbName".

查看源码

REST 连接

1. public static void main(String[] args) throws SQLException {
2. String jdbcUrl = "jdbc:TAOS-RS://localhost:6041?user=root&password=taosdata";
3. Connection conn = DriverManager.getConnection(jdbcUrl);
4. System.out.println("Connected");
5. conn.close();
6. }

查看源码

使用 REST 连接时,如果查询数据量比较大,还可开启批量拉取功能。

开启批量拉取功能

1. public static void main(String[] args) throws SQLException {
2. String jdbcUrl = "jdbc:TAOS-RS://localhost:6041?user=root&password=taosdata";
3. Properties connProps = new Properties();
4. connProps.setProperty(TSDBDriver.PROPERTY_KEY_BATCH_LOAD, "true");
5. Connection conn = DriverManager.getConnection(jdbcUrl, connProps);
6. System.out.println("Connected");
7. conn.close();
8. }

查看源码

更多连接参数配置,参考Java 连接器

原生连接

1. import taos

4. def test_connection():
5. # all parameters are optional.
6. # if database is specified,
7. # then it must exist.
8. conn = taos.connect(host="localhost",
9. port=6030,
10. user="root",
11. password="taosdata",
12. database="log")
13. print('client info:', conn.client_info)
14. print('server info:', conn.server_info)
15. conn.close()

18. if __name__ == "__main__":
19. test_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. var taosDSN = "root:taosdata@tcp(localhost:6030)/"
13. taos, err := sql.Open("taosSql", taosDSN)
14. if err != nil {
15. log.Fatalln("failed to connect TDengine, err:", err)
16. return
17. }
18. fmt.Println("Connected")
19. defer taos.Close()
20. }

22. // use
23. // var taosDSN = "root:taosdata@tcp(localhost:6030)/dbName"
24. // if you want to connect a specified database named "dbName".

查看源码

REST 连接

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. var taosDSN = "root:taosdata@http(localhost:6041)/"
13. taos, err := sql.Open("taosRestful", taosDSN)
14. if err != nil {
15. log.Fatalln("failed to connect TDengine, err:", err)
16. return
17. }
18. fmt.Println("Connected")
19. defer taos.Close()
20. }

22. // use
23. // var taosDSN = "root:taosdata@http(localhost:6041)/dbName"
24. // if you want to connect a specified database named "dbName".

查看源码

使用高级封装

也可以使用 driver-go 的 af 包建立连接。这个模块封装了 TDengine 的高级功能, 如:参数绑定、订阅等。

使用 af 包建立原生连接

1. package main

3. import (
4. "fmt"
5. "log"

7. "github.com/taosdata/driver-go/v3/af"
8. )

10. func main() {
11. conn, err := af.Open("localhost", "root", "taosdata", "", 6030)
12. defer conn.Close()
13. if err != nil {
14. log.Fatalln("failed to connect, err:", err)
15. } else {
16. fmt.Println("connected")
17. }
18. }

查看源码

原生连接/REST 连接

1. use taos::*;

3. #[tokio::main]
4. async fn main() -> Result<(), Error> {
5. #[allow(unused_variables)]
6. let taos = TaosBuilder::from_dsn("taos://")?.build()?;
7. println!("Connected");
8. Ok(())
9. }

查看源码

建立连接 - 图11note

对于 Rust 连接器, 连接方式的不同只体现在使用的特性不同。如果启用了 “rest” 特性,那么只有 RESTful 的实现会被编译进来。

原生连接

1. //A cursor also needs to be initialized in order to interact with TDengine from Node.js.
2. const taos = require("@tdengine/client");
3. var conn = taos.connect({
4. host: "127.0.0.1",
5. user: "root",
6. password: "taosdata",
7. config: "/etc/taos",
8. port: 0,
9. });
10. var cursor = conn.cursor(); // Initializing a new cursor

12. //Close a connection
13. conn.close();

查看源码

REST 连接

1. const { options, connect } = require("@tdengine/rest");

3. async function test() {
4. options.path = "/rest/sql";
5. options.host = "localhost";
6. options.port = 6041;
7. let conn = connect(options);
8. let cursor = conn.cursor();
9. try {
10. let res = await cursor.query("SELECT server_version()");
11. console.log("res.getResult()",res.getResult());
12. } catch (err) {
13. console.log(err);
14. }
15. }
16. test();

查看源码

原生连接

1. using TDengineDriver;

3. namespace TDengineExample
4. {

6. internal class ConnectExample
7. {
8. static void Main(String[] args)
9. {
10. string host = "localhost";
11. short port = 6030;
12. string username = "root";
13. string password = "taosdata";
14. string dbname = "";

16. var conn = TDengine.Connect(host, username, password, dbname, port);
17. if (conn == IntPtr.Zero)
18. {
19. throw new Exception("Connect to TDengine failed");
20. }
21. else
22. {
23. Console.WriteLine("Connect to TDengine success");
24. }
25. TDengine.Close(conn);
26. TDengine.Cleanup();
27. }
28. }
29. }

查看源码

WebSocket 连接

1. using System;
2. using TDengineWS.Impl;

4. namespace Examples
5. {
6. public class WSConnExample
7. {
8. static int Main(string[] args)
9. {
10. string DSN = "ws://root:taosdata@127.0.0.1:6041/test";
11. IntPtr wsConn = LibTaosWS.WSConnectWithDSN(DSN);

13. if (wsConn == IntPtr.Zero)
14. {
15. Console.WriteLine("get WS connection failed");
16. return -1;
17. }
18. else
19. {
20. Console.WriteLine("Establish connect success.");
21. // close connection.
22. LibTaosWS.WSClose(wsConn);
23. }

25. return 0;
26. }
27. }
28. }

查看源码

原生连接

1. library("DBI")
2. library("rJava")
3. library("RJDBC")

5. args<- commandArgs(trailingOnly = TRUE)
6. driver_path = args[1] # path to jdbc-driver for example: "/root/taos-jdbcdriver-3.0.0-dist.jar"
7. driver = JDBC("com.taosdata.jdbc.TSDBDriver", driver_path)
8. conn = dbConnect(driver, "jdbc:TAOS://127.0.0.1:6030/?user=root&password=taosdata")
9. dbGetQuery(conn, "SELECT server_version()")
10. dbDisconnect(conn)

查看源码

原生连接

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. // if don't want to connect to a default db, set it to NULL or ""
12. const char *db = NULL;
13. uint16_t    port = 0;  // 0 means use the default port
14. TAOS       *taos = taos_connect(host, user, passwd, db, port);
15. if (taos == NULL) {
16. int   errno = taos_errno(NULL);
17. char *msg = taos_errstr(NULL);
18. printf("%d, %s\n", errno, msg);
19. } else {
20. printf("connected\n");
21. taos_close(taos);
22. }
23. taos_cleanup();
24. }

查看源码

原生连接

1. <?php

3. use TDengine\Connection;
4. use TDengine\Exception\TDengineException;

6. try {
7. // instantiate
8. $host = 'localhost';
9. $port = 6030;
10. $username = 'root';
11. $password = 'taosdata';
12. $dbname = null;
13. $connection = new Connection($host, $port, $username, $password, $dbname);

15. // connect
16. $connection->connect();
17. } catch (TDengineException $e) {
18. // throw exception
19. throw $e;
20. }

查看源码

建立连接 - 图12tip

如果建立连接失败,大部分情况下是 FQDN 或防火墙的配置不正确,详细的排查方法请看《常见问题及反馈》中的“遇到错误 Unable to establish connection, 我怎么办?”