Connect
Any application programs running on any kind of platform can access TDengine through the REST API provided by TDengine. For details, please refer to REST API. Additionally, application programs can use the connectors of multiple programming languages including C/C++, Java, Python, Go, Node.js, C#, Rust to access TDengine. This chapter describes how to establish a connection to TDengine and briefly introduces how to install and use connectors. TDengine community also provides connectors in LUA and PHP languages. For details about the connectors, please refer to Connectors.
Establish Connection
There are two ways for a connector to establish connections to TDengine:
- Connection through the REST API provided by the taosAdapter component, this way is called "REST connection" hereinafter.
- Connection through the TDengine client driver (taosc), this way is called "Native connection" hereinafter.
Key differences:
- The TDengine client driver (taosc) has the highest performance with all the features of TDengine like Parameter Binding, Subscription, etc.
- The TDengine client driver (taosc) is not supported across all platforms, and applications built on taosc may need to be modified when updating taosc to newer versions.
- The REST connection is more accessible with cross-platform support, however it results in a 30% performance downgrade.
Install Client Driver taosc
If you are choosing to use the native connection and the the application is not on the same host as TDengine server, the TDengine client driver taosc needs to be installed on the application host. If choosing to use the REST connection or the application is on the same host as TDengine server, this step can be skipped. It's better to use same version of taosc as the TDengine server.
Install
- Linux
- Windows
- Download the TDengine client installation package
-
Unzip
Download the package to any directory the current user has read/write permission. Then execute
tar -xzvf TDengine-client-VERSION.tar.gz
command. The VERSION should be the version of the package you just downloaded. -
Execute the install script
Once the package is unzipped, you will see the following files in the directory:
- _ install_client.sh_: install script
- _ taos.tar.gz_: client driver package
- _ driver_: TDengine client driver
- examples: some example programs of different programming languages (C/C#/go/JDBC/MATLAB/python/R)
You can run
install_client.sh
to install it. -
Edit taos.cfg
Edit
taos.cfg
file (full path is/etc/taos/taos.cfg
by default), modifyfirstEP
with actual TDengine server's End Point, for exampleh1.tdengine.com:6030
-
If the computer does not run the TDengine service but installs the TDengine client driver, then you need to config
firstEP
intaos.cfg
only, and there is no need to configureFQDN
; -
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.
-
Download the client installation package
Enter your email to receive the download linkEnter your information to receive a download linkAgree to TDengine to contact me via this email address -
Execute the installer, select the default value as prompted, and complete the installation
-
Installation path
The default installation path is C:\TDengine, including the following files (directories).
- taos.exe : TDengine CLI command-line program
- cfg : configuration file directory
- driver: client driver dynamic link library
- examples: sample programs bash/C/C#/go/JDBC/Python/Node.js
- include: header files
- log : log file
- unins000.exe: uninstaller
-
configure taos.cfg
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
.
- 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.taosd.com
.. - Uninstall: Run unins000.exe to uninstall the TDengine client driver.
Verify
After the above installation and configuration are done and making sure TDengine service is already started and in service, the TDengine command-line interface taos
can be launched to access TDengine.
- Linux
- Windows
Execute TDengine CLI program taos
directly from the Linux shell to connect to the TDengine service and enter the TDengine CLI interface, as shown in the following example.
$ 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.001198s)
taos>
Go to the C:\TDengine
directory from cmd
and execute TDengine CLI program taos.exe
directly to connect to the TDengine service and enter the TDengine CLI interface, for example, as follows:
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>
Install Connectors
- Java
- Python
- Go
- Rust
- Node.js
- C#
- R
- C
- PHP
If maven
is used to manage the projects, what needs to be done is only adding below dependency in pom.xml
.
<dependency>
<groupId>com.taosdata.jdbc</groupId>
<artifactId>taos-jdbcdriver</artifactId>
<version>2.0.38</version>
</dependency>
Install from PyPI using pip
:
pip install taospy
Install from Git URL:
pip install git+https://github.com/taosdata/taos-connector-python.git
Just need to add driver-go
dependency in go.mod
.
module goexample
go 1.17
require github.com/taosdata/driver-go/v2 v2.0.5
driver-go
uses cgo
to wrap the APIs provided by taosc, while cgo
needs gcc
to compile source code in C language, so please make sure you have proper gcc
on your system.
Just need to add libtaos
dependency in Cargo.toml
.
[dependencies]
libtaos = { version = "0.4.2"}
Rust connector uses different features to distinguish the way to establish connection. To establish REST connection, please enable rest
feature.
libtaos = { version = "*", features = ["rest"] }
Node.js connector provides different ways of establishing connections by providing different packages.
- Install Node.js Native Connector
npm i td2.0-connector
It's recommend to use Node whose version is between node-v12.8.0
and node-v13.0.0
.
- Install Node.js REST Connector
npm i td2.0-rest-connector
Just need to add the reference to TDengine.Connector in the project configuration file.
<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="1.0.6" />
</ItemGroup>
</Project>
Or add by dotnet
command.
dotnet add package TDengine.Connector
The sample code below are based on dotnet6.0, they may need to be adjusted if your dotnet version is not exactly same.
- Download taos-jdbcdriver-version-dist.jar.
- Install the dependency package
RJDBC
:
install.packages("RJDBC")
If the client driver (taosc) is already installed, then the C connector is already available.
Download Source Code Package and Unzip:
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
Version number
v1.0.2
is only for example, it can be replaced to any newer version, please check available version from TDengine PHP Connector Releases.
Non-Swoole Environment:
phpize && ./configure && make -j && make install
Specify TDengine Location:
phpize && ./configure --with-tdengine-dir=/usr/local/Cellar/tdengine/2.4.0.0 && make -j && make install
--with-tdengine-dir=
is followed by the TDengine installation location. This way is useful in case TDengine location can't be found automatically or macOS.
Swoole Environment:
phpize && ./configure --enable-swoole && make -j && make install
Enable The Extension:
Option One: Add extension=tdengine
in php.ini
Option Two: Specify the extension on CLI php -d extension=tdengine test.php
Establish Connection
Prior to establishing connection, please make sure TDengine is already running and accessible. The following sample code assumes TDengine is running on the same host as the client program, with FQDN configured to "localhost" and serverPort configured to "6030".
- Java
- Python
- Go
- Rust
- Node.js
- C#
- R
- C
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();
}
When using REST connection, the feature of bulk pulling can be enabled if the size of resulting data set is huge.
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();
}
More configuration about connection,please refer to Java Connector
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()
Unified Database Access Interface
package main
import (
"database/sql"
"fmt"
_ "github.com/taosdata/driver-go/v2/taosSql"
)
func main() {
var taosDSN = "root:taosdata@tcp(localhost:6030)/"
taos, err := sql.Open("taosSql", taosDSN)
if err != nil {
fmt.Println("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"
_ "github.com/taosdata/driver-go/v2/taosRestful"
)
func main() {
var taosDSN = "root:taosdata@http(localhost:6041)/"
taos, err := sql.Open("taosRestful", taosDSN)
if err != nil {
fmt.Println("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".
Advanced Features
The af package of driver-go can also be used to establish connection, with this way some advanced features of TDengine, like parameter binding and subscription, can be used.
package main
import (
"fmt"
"github.com/taosdata/driver-go/v2/af"
)
func main() {
conn, err := af.Open("localhost", "root", "taosdata", "", 6030)
defer conn.Close()
if err != nil {
fmt.Println("failed to connect, err:", err)
} else {
fmt.Println("connected")
}
}
use libtaos::*;
fn taos_connect() -> Result<Taos, Error> {
TaosCfgBuilder::default()
.ip("localhost")
.user("root")
.pass("taosdata")
// .db("log") // remove comment if you want to connect to database log by default.
.port(6030u16)
.build()
.expect("TaosCfg builder error")
.connect()
}
fn main() {
#[allow(unused_variables)]
let taos = taos_connect().unwrap();
println!("Connected")
}
For Rust connector, the connection depends on the feature being used. If "rest" feature is enabled, then only the implementation for "rest" is compiled and packaged.
const taos = require("td2.0-connector");
var conn = taos.connect({
host: "localhost",
port: 6030,
user: "root",
password: "taosdata",
});
conn.close();
// run with: node connect.js
// output:
// Successfully connected to TDengine
const { options, connect } = require("td2.0-rest-connector");
async function test() {
options.path = "/rest/sqlt";
options.host = "localhost";
let conn = connect(options);
let cursor = conn.cursor();
try {
let res = await cursor.query("SELECT server_version()");
res.toString();
} catch (err) {
console.log(err);
}
}
test();
// output:
// server_version() |
// ===================
// 2.4.0.12 |
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)
{
Console.WriteLine("Connect to TDengine failed");
}
else
{
Console.WriteLine("Connect to TDengine success");
}
TDengine.Close(conn);
TDengine.Cleanup();
}
}
}
C# connector supports only native connection for now.
library("DBI")
library("rJava")
library("RJDBC")
args<- commandArgs(trailingOnly = TRUE)
driver_path = args[1] # path to jdbc-driver for example: "/root/taos-jdbcdriver-2.0.37-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()")
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();
}
If the connection fails, in most cases it's caused by improper configuration for FQDN or firewall. Please refer to the section "Unable to establish connection" in FAQ.