建立连接

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
  1. 下载客户端安装包

    下载 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 进行安装。
  4. 配置 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: 卸载程序
  6. 配置 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
  2. taos> show databases;
  3. name |
  4. =================================
  5. information_schema |
  6. performance_schema |
  7. db |
  8. Query OK, 3 rows in database (0.019154s)
  9. 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)
  9. taos>

在 macOS shell 下直接执行 taos 连接到 TDengine 服务,进入到 TDengine CLI 界面,示例如下:

  1. $ taos
  2. taos> show databases;
  3. name |
  4. =================================
  5. information_schema |
  6. performance_schema |
  7. db |
  8. Query OK, 3 rows in database (0.019154s)
  9. 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
  2. go 1.17
  3. 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">
  2. <PropertyGroup>
  3. <OutputType>Exe</OutputType>
  4. <TargetFramework>net6.0</TargetFramework>
  5. <ImplicitUsings>enable</ImplicitUsings>
  6. <Nullable>enable</Nullable>
  7. <StartupObject>TDengineExample.AsyncQueryExample</StartupObject>
  8. </PropertyGroup>
  9. <ItemGroup>
  10. <PackageReference Include="TDengine.Connector" Version="3.0.0" />
  11. </ItemGroup>
  12. </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;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.SQLException;
  5. import java.util.Properties;
  6. import com.taosdata.jdbc.TSDBDriver;
  7. public class JNIConnectExample {
  8. public static void main(String[] args) throws SQLException {
  9. String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata";
  10. Properties connProps = new Properties();
  11. connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
  12. connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
  13. connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
  14. Connection conn = DriverManager.getConnection(jdbcUrl, connProps);
  15. System.out.println("Connected");
  16. conn.close();
  17. }
  18. }
  19. // use
  20. // String jdbcUrl = "jdbc:TAOS://localhost:6030/dbName?user=root&password=taosdata";
  21. // 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
  2. def test_connection():
  3. # all parameters are optional.
  4. # if database is specified,
  5. # then it must exist.
  6. conn = taos.connect(host="localhost",
  7. port=6030,
  8. user="root",
  9. password="taosdata",
  10. database="log")
  11. print('client info:', conn.client_info)
  12. print('server info:', conn.server_info)
  13. conn.close()
  14. if __name__ == "__main__":
  15. test_connection()

查看源码

使用数据库访问统一接口

原生连接

  1. package main
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "log"
  6. _ "github.com/taosdata/driver-go/v3/taosSql"
  7. )
  8. func main() {
  9. var taosDSN = "root:taosdata@tcp(localhost:6030)/"
  10. taos, err := sql.Open("taosSql", taosDSN)
  11. if err != nil {
  12. log.Fatalln("failed to connect TDengine, err:", err)
  13. return
  14. }
  15. fmt.Println("Connected")
  16. defer taos.Close()
  17. }
  18. // use
  19. // var taosDSN = "root:taosdata@tcp(localhost:6030)/dbName"
  20. // if you want to connect a specified database named "dbName".

查看源码

REST 连接

  1. package main
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "log"
  6. _ "github.com/taosdata/driver-go/v3/taosRestful"
  7. )
  8. func main() {
  9. var taosDSN = "root:taosdata@http(localhost:6041)/"
  10. taos, err := sql.Open("taosRestful", taosDSN)
  11. if err != nil {
  12. log.Fatalln("failed to connect TDengine, err:", err)
  13. return
  14. }
  15. fmt.Println("Connected")
  16. defer taos.Close()
  17. }
  18. // use
  19. // var taosDSN = "root:taosdata@http(localhost:6041)/dbName"
  20. // if you want to connect a specified database named "dbName".

查看源码

使用高级封装

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

使用 af 包建立原生连接

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "github.com/taosdata/driver-go/v3/af"
  6. )
  7. func main() {
  8. conn, err := af.Open("localhost", "root", "taosdata", "", 6030)
  9. defer conn.Close()
  10. if err != nil {
  11. log.Fatalln("failed to connect, err:", err)
  12. } else {
  13. fmt.Println("connected")
  14. }
  15. }

查看源码

原生连接/REST 连接

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

查看源码

建立连接 - 图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
  11. //Close a connection
  12. conn.close();

查看源码

REST 连接

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

查看源码

原生连接

  1. using TDengineDriver;
  2. namespace TDengineExample
  3. {
  4. internal class ConnectExample
  5. {
  6. static void Main(String[] args)
  7. {
  8. string host = "localhost";
  9. short port = 6030;
  10. string username = "root";
  11. string password = "taosdata";
  12. string dbname = "";
  13. var conn = TDengine.Connect(host, username, password, dbname, port);
  14. if (conn == IntPtr.Zero)
  15. {
  16. throw new Exception("Connect to TDengine failed");
  17. }
  18. else
  19. {
  20. Console.WriteLine("Connect to TDengine success");
  21. }
  22. TDengine.Close(conn);
  23. TDengine.Cleanup();
  24. }
  25. }
  26. }

查看源码

WebSocket 连接

  1. using System;
  2. using TDengineWS.Impl;
  3. namespace Examples
  4. {
  5. public class WSConnExample
  6. {
  7. static int Main(string[] args)
  8. {
  9. string DSN = "ws://root:taosdata@127.0.0.1:6041/test";
  10. IntPtr wsConn = LibTaosWS.WSConnectWithDSN(DSN);
  11. if (wsConn == IntPtr.Zero)
  12. {
  13. Console.WriteLine("get WS connection failed");
  14. return -1;
  15. }
  16. else
  17. {
  18. Console.WriteLine("Establish connect success.");
  19. // close connection.
  20. LibTaosWS.WSClose(wsConn);
  21. }
  22. return 0;
  23. }
  24. }
  25. }

查看源码

原生连接

  1. library("DBI")
  2. library("rJava")
  3. library("RJDBC")
  4. args<- commandArgs(trailingOnly = TRUE)
  5. driver_path = args[1] # path to jdbc-driver for example: "/root/taos-jdbcdriver-3.0.0-dist.jar"
  6. driver = JDBC("com.taosdata.jdbc.TSDBDriver", driver_path)
  7. conn = dbConnect(driver, "jdbc:TAOS://127.0.0.1:6030/?user=root&password=taosdata")
  8. dbGetQuery(conn, "SELECT server_version()")
  9. 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"
  6. int main() {
  7. const char *host = "localhost";
  8. const char *user = "root";
  9. const char *passwd = "taosdata";
  10. // if don't want to connect to a default db, set it to NULL or ""
  11. const char *db = NULL;
  12. uint16_t port = 0; // 0 means use the default port
  13. TAOS *taos = taos_connect(host, user, passwd, db, port);
  14. if (taos == NULL) {
  15. int errno = taos_errno(NULL);
  16. char *msg = taos_errstr(NULL);
  17. printf("%d, %s\n", errno, msg);
  18. } else {
  19. printf("connected\n");
  20. taos_close(taos);
  21. }
  22. taos_cleanup();
  23. }

查看源码

原生连接

  1. <?php
  2. use TDengine\Connection;
  3. use TDengine\Exception\TDengineException;
  4. try {
  5. // instantiate
  6. $host = 'localhost';
  7. $port = 6030;
  8. $username = 'root';
  9. $password = 'taosdata';
  10. $dbname = null;
  11. $connection = new Connection($host, $port, $username, $password, $dbname);
  12. // connect
  13. $connection->connect();
  14. } catch (TDengineException $e) {
  15. // throw exception
  16. throw $e;
  17. }

查看源码

建立连接 - 图12tip

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