建立连接
TDengine 提供了丰富的应用程序开发接口,为了便于用户快速开发自己的应用,TDengine 支持了多种编程语言的连接器,其中官方连接器包括支持 C/C++、Java、Python、Go、Node.js、C#、Rust、Lua(社区贡献)和 PHP (社区贡献)的连接器。这些连接器支持使用原生接口(taosc)和 REST 接口(部分语言暂不支持)连接 TDengine 集群。社区开发者也贡献了多个非官方连接器,例如 ADO.NET 连接器、Lua 连接器和 PHP 连接器。
连接器建立连接的方式
连接器建立连接的方式,TDengine 提供两种:
- 通过 taosAdapter 组件提供的 REST API 建立与 taosd 的连接,这种连接方式下文中简称“REST 连接”
- 通过客户端驱动程序 taosc 直接与服务端程序 taosd 建立连接,这种连接方式下文中简称“原生连接”。
无论使用何种方式建立连接,连接器都提供了相同或相似的 API 操作数据库,都可以执行 SQL 语句,只是初始化连接的方式稍有不同,用户在使用上不会感到什么差别。
关键不同点在于:
安装客户端驱动 taosc
如果选择原生连接,而且应用程序不在 TDengine 同一台服务器上运行,你需要先安装客户端驱动,否则可以跳过此一步。为避免客户端驱动和服务端不兼容,请使用一致的版本。
安装步骤
- Linux
- Windows
- macOS
下载客户端安装包
下载 TDengine输入您的电子邮箱以接收下载链接同意涛思数据通过此邮件地址联系我解压缩软件包
将软件包放置在当前用户可读写的任意目录下,然后执行下面的命令:
tar -xzvf TDengine-client-VERSION.tar.gz
其中 VERSION 需要替换为实际版本的字符串。执行安装脚本
解压软件包之后,会在解压目录下看到以下文件(目录):
- 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
tip
- 如本机没有部署 TDengine 服务,仅安装了应用驱动,则
taos.cfg
中仅需配置firstEP
,无需在本机配置FQDN
。 - 为防止与服务器端连接时出现“Unable to resolve FQDN”错误,建议确认本机的
/etc/hosts
文件已经配置了服务器正确的 FQDN 值,或配置好了 DNS 服务。
下载客户端安装包
下载 TDengine输入您的电子邮箱以接收下载链接同意涛思数据通过此邮件地址联系我执行安装程序,按提示选择默认值,完成安装
安装路径
默认安装路径为: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
。
tip
- 如利用 FQDN 连接服务器,必须确认本机网络环境 DNS 已配置好,或在 hosts 文件中添加 FQDN 寻址记录, 如编辑 C:\Windows\system32\drivers\etc\hosts,添加类似如下的记录:
192.168.1.99 h1.taos.com
- 卸载:运行 unins000.exe 可卸载 TDengine 应用驱动。
下载客户端安装包
下载 TDengine输入您的电子邮箱以接收下载链接同意涛思数据通过此邮件地址联系我执行安装程序,按提示选择默认值,完成安装。如果安装被阻止,可以右键或者按 Ctrl 点击安装包,选择
打开
。配置 taos.cfg
编辑
taos.cfg
文件(默认路径/etc/taos/taos.cfg),将firstEP
修改为 TDengine 服务器的 End Point,例如:h1.tdengine.com:6030
tip
- 如本机没有部署 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 界面,示例如下:
$ taos
taos> show databases;
name |
=================================
information_schema |
performance_schema |
db |
Query OK, 3 rows in database (0.019154s)
taos>
在 cmd 下进入到 C:\TDengine 目录下直接执行 taos.exe
,连接到 TDengine 服务,进入到 TDengine CLI 界面,示例如下:
taos> show databases;
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 |
===============================================================================================================================================================================================================================================================================================================================================================================================================================
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 |
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 |
test | 2022-08-04 16:46:40.506 | 2 | 0 | 1 | off | 14400m | 5256000m,5256000m,5256000m | 96 | 4 | 256 |
100 | 4096 | 2 | ms | ready | NULL | false | none | 1 | 1 | 3000 | 0 | 0 | 0 | 0 |
Query OK, 3 rows in database (0.123000s)
taos>
在 macOS shell 下直接执行 taos
连接到 TDengine 服务,进入到 TDengine CLI 界面,示例如下:
$ taos
taos> show databases;
name |
=================================
information_schema |
performance_schema |
db |
Query OK, 3 rows in database (0.019154s)
taos>
安装连接器
- Java
- Python
- Go
- Rust
- Node.js
- C#
- R
- C
- PHP
如果使用 Maven 管理项目,只需在 pom.xml 中加入以下依赖。
<dependency>
<groupId>com.taosdata.jdbc</groupId>
<artifactId>taos-jdbcdriver</artifactId>
<version>3.2.4</version>
</dependency>
使用 pip
从 PyPI 安装:
pip install taospy
从 Git URL 安装:
pip install git+https://github.com/taosdata/taos-connector-python.git
编辑 go.mod
添加 driver-go
依赖即可。
module goexample
go 1.17
require github.com/taosdata/driver-go/v3 latest
note
driver-go 使用 cgo 封装了 taosc 的 API。cgo 需要使用 GCC 编译 C 的源码。因此需要确保你的系统上有 GCC。
编辑 Cargo.toml
添加 libtaos
依赖即可。
[dependencies]
libtaos = { version = "0.4.2"}
info
Rust 连接器通过不同的特性区分不同的连接方式。如果要建立 REST 连接,需要开启 rest
特性:
libtaos = { version = "*", features = ["rest"] }
Node.js 连接器通过不同的包提供不同的连接方式。
- 安装 Node.js 原生连接器
npm install @tdengine/client
note
推荐 Node 版本大于等于 node-v12.8.0
小于 node-v13.0.0
- 安装 Node.js REST 连接器
npm install @tdengine/rest
编辑项目配置文件中添加 TDengine.Connector 的引用即可:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<StartupObject>TDengineExample.AsyncQueryExample</StartupObject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="TDengine.Connector" Version="3.0.0" />
</ItemGroup>
</Project>
也可通过 dotnet 命令添加:
dotnet add package TDengine.Connector
note
以下示例代码,均基于 dotnet6.0,如果使用其它版本,可能需要做适当调整。
- 下载 taos-jdbcdriver-version-dist.jar。
- 安装 R 的依赖包
RJDBC
:
install.packages("RJDBC")
如果已经安装了 TDengine 服务端软件或 TDengine 客户端驱动 taosc, 那么已经安装了 C 连接器,无需额外操作。
下载代码并解压:
curl -L -o php-tdengine.tar.gz https://github.com/Yurunsoft/php-tdengine/archive/refs/tags/v1.0.2.tar.gz \
&& mkdir php-tdengine \
&& tar -xzf php-tdengine.tar.gz -C php-tdengine --strip-components=1
版本
v1.0.2
只是示例,可替换为任意更新的版本,可在 TDengine PHP Connector 发布历史 中查看可用版本。
非 Swoole 环境:
phpize && ./configure && make -j && make install
手动指定 TDengine 目录:
phpize && ./configure --with-tdengine-dir=/usr/local/Cellar/tdengine/3.0.0.0 && make -j && make install
--with-tdengine-dir=
后跟上 TDengine 目录。 适用于默认找不到的情况,或者 macOS 系统用户。
Swoole 环境:
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
package com.taos.example;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import com.taosdata.jdbc.TSDBDriver;
public class JNIConnectExample {
public static void main(String[] args) throws SQLException {
String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata";
Properties connProps = new Properties();
connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
Connection conn = DriverManager.getConnection(jdbcUrl, connProps);
System.out.println("Connected");
conn.close();
}
}
// use
// String jdbcUrl = "jdbc:TAOS://localhost:6030/dbName?user=root&password=taosdata";
// if you want to connect a specified database named "dbName".
public static void main(String[] args) throws SQLException {
String jdbcUrl = "jdbc:TAOS-RS://localhost:6041?user=root&password=taosdata";
Connection conn = DriverManager.getConnection(jdbcUrl);
System.out.println("Connected");
conn.close();
}
使用 REST 连接时,如果查询数据量比较大,还可开启批量拉取功能。
public static void main(String[] args) throws SQLException {
String jdbcUrl = "jdbc:TAOS-RS://localhost:6041?user=root&password=taosdata";
Properties connProps = new Properties();
connProps.setProperty(TSDBDriver.PROPERTY_KEY_BATCH_LOAD, "true");
Connection conn = DriverManager.getConnection(jdbcUrl, connProps);
System.out.println("Connected");
conn.close();
}
更多连接参数配置,参考Java 连接器
import taos
def test_connection():
# all parameters are optional.
# if database is specified,
# then it must exist.
conn = taos.connect(host="localhost",
port=6030,
user="root",
password="taosdata",
database="log")
print('client info:', conn.client_info)
print('server info:', conn.server_info)
conn.close()
if __name__ == "__main__":
test_connection()
使用数据库访问统一接口
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/taosdata/driver-go/v3/taosSql"
)
func main() {
var taosDSN = "root:taosdata@tcp(localhost:6030)/"
taos, err := sql.Open("taosSql", taosDSN)
if err != nil {
log.Fatalln("failed to connect TDengine, err:", err)
return
}
fmt.Println("Connected")
defer taos.Close()
}
// use
// var taosDSN = "root:taosdata@tcp(localhost:6030)/dbName"
// if you want to connect a specified database named "dbName".
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/taosdata/driver-go/v3/taosRestful"
)
func main() {
var taosDSN = "root:taosdata@http(localhost:6041)/"
taos, err := sql.Open("taosRestful", taosDSN)
if err != nil {
log.Fatalln("failed to connect TDengine, err:", err)
return
}
fmt.Println("Connected")
defer taos.Close()
}
// use
// var taosDSN = "root:taosdata@http(localhost:6041)/dbName"
// if you want to connect a specified database named "dbName".
使用高级封装
也可以使用 driver-go 的 af 包建立连接。这个模块封装了 TDengine 的高级功能, 如:参数绑定、订阅等。
package main
import (
"fmt"
"log"
"github.com/taosdata/driver-go/v3/af"
)
func main() {
conn, err := af.Open("localhost", "root", "taosdata", "", 6030)
defer conn.Close()
if err != nil {
log.Fatalln("failed to connect, err:", err)
} else {
fmt.Println("connected")
}
}
use taos::*;
#[tokio::main]
async fn main() -> Result<(), Error> {
#[allow(unused_variables)]
let taos = TaosBuilder::from_dsn("taos://")?.build()?;
println!("Connected");
Ok(())
}
note
对于 Rust 连接器, 连接方式的不同只体现在使用的特性不同。如果启用了 "rest" 特性,那么只有 RESTful 的实现会被编译进来。
//A cursor also needs to be initialized in order to interact with TDengine from Node.js.
const taos = require("@tdengine/client");
var conn = taos.connect({
host: "127.0.0.1",
user: "root",
password: "taosdata",
config: "/etc/taos",
port: 0,
});
var cursor = conn.cursor(); // Initializing a new cursor
//Close a connection
conn.close();
const { options, connect } = require("@tdengine/rest");
async function test() {
options.path = "/rest/sql";
options.host = "localhost";
options.port = 6041;
let conn = connect(options);
let cursor = conn.cursor();
try {
let res = await cursor.query("SELECT server_version()");
console.log("res.getResult()",res.getResult());
} catch (err) {
console.log(err);
}
}
test();
using TDengineDriver;
namespace TDengineExample
{
internal class ConnectExample
{
static void Main(String[] args)
{
string host = "localhost";
short port = 6030;
string username = "root";
string password = "taosdata";
string dbname = "";
var conn = TDengine.Connect(host, username, password, dbname, port);
if (conn == IntPtr.Zero)
{
throw new Exception("Connect to TDengine failed");
}
else
{
Console.WriteLine("Connect to TDengine success");
}
TDengine.Close(conn);
TDengine.Cleanup();
}
}
}
using System;
using TDengineWS.Impl;
namespace Examples
{
public class WSConnExample
{
static int Main(string[] args)
{
string DSN = "ws://root:taosdata@127.0.0.1:6041/test";
IntPtr wsConn = LibTaosWS.WSConnectWithDSN(DSN);
if (wsConn == IntPtr.Zero)
{
Console.WriteLine("get WS connection failed");
return -1;
}
else
{
Console.WriteLine("Establish connect success.");
// close connection.
LibTaosWS.WSClose(wsConn);
}
return 0;
}
}
}
library("DBI")
library("rJava")
library("RJDBC")
args<- commandArgs(trailingOnly = TRUE)
driver_path = args[1] # path to jdbc-driver for example: "/root/taos-jdbcdriver-3.2.4-dist.jar"
driver = JDBC("com.taosdata.jdbc.TSDBDriver", driver_path)
conn = dbConnect(driver, "jdbc:TAOS://127.0.0.1:6030/?user=root&password=taosdata")
dbGetQuery(conn, "SELECT server_version()")
dbSendUpdate(conn, "create database if not exists rtest")
dbSendUpdate(conn, "create table if not exists rtest.test (ts timestamp, current float, voltage int, devname varchar(20))")
dbSendUpdate(conn, "insert into rtest.test values (now, 1.2, 220, 'test')")
dbGetQuery(conn, "select * from rtest.test")
dbDisconnect(conn)
// compile with
// gcc connect_example.c -o connect_example -ltaos
#include <stdio.h>
#include <stdlib.h>
#include "taos.h"
int main() {
const char *host = "localhost";
const char *user = "root";
const char *passwd = "taosdata";
// if don't want to connect to a default db, set it to NULL or ""
const char *db = NULL;
uint16_t port = 0; // 0 means use the default port
TAOS *taos = taos_connect(host, user, passwd, db, port);
if (taos == NULL) {
int errno = taos_errno(NULL);
char *msg = taos_errstr(NULL);
printf("%d, %s\n", errno, msg);
} else {
printf("connected\n");
taos_close(taos);
}
taos_cleanup();
}
<?php
use TDengine\Connection;
use TDengine\Exception\TDengineException;
try {
// instantiate
$host = 'localhost';
$port = 6030;
$username = 'root';
$password = 'taosdata';
$dbname = null;
$connection = new Connection($host, $port, $username, $password, $dbname);
// connect
$connection->connect();
} catch (TDengineException $e) {
// throw exception
throw $e;
}
tip
如果建立连接失败,大部分情况下是 FQDN 或防火墙的配置不正确,详细的排查方法请看《常见问题及反馈》中的“遇到错误 Unable to establish connection, 我怎么办?”