Connect to TDengine
Any application running on any platform can access TDengine through the REST API provided by TDengine. For information, see REST API. Applications can also use the client libraries for various programming languages, including C/C++, Java, Python, Go, Node.js, C#, and Rust, to access TDengine. These client libraries support connecting to TDengine clusters using both native interfaces (taosc). Some client libraries also support connecting over a REST interface. Community developers have also contributed several unofficial client libraries, such as the ADO.NET, Lua, and PHP libraries.
Establish Connection
There are three ways for a client library to establish connections to TDengine:
- Native connection through the TDengine client driver (taosc).
- REST connection through the REST API provided by the taosAdapter component.
- Websocket connection provided by the taosAdapter component.
For these ways of connections, client libraries provide similar APIs for performing operations and running SQL statements on your databases. The main difference is the method of establishing the connection, which is not visible to users.
Key differences:
- For a Native connection, the client driver taosc and the server TDengine version must be compatible.
- For a REST connection, users do not need to install the client driver taosc, providing the advantage of cross-platform ease of use. However, functions such as data subscription and binary data types are not available. Additionally, compared to Native and Websocket connections, a REST connection has the worst performance.
- For a Websocket connection, users also do not need to install the client driver taosc.
- To connect to a cloud service instance, you need to use the REST connection or Websocket connection.
Normally we recommend using Websocket connection.
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
- MacOS
- Download the 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
- _ package.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.
-
configure 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
Download TDengineEnter your information to receive a download linkI agree to receive communications from TDengine and to allow TDengine to store and process my personal data. -
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
- taosadapter.exe: server-side executable that provides RESTful services and accepts writing requests from a variety of other software
- taosBenchmark.exe: TDengine testing tool
- 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.
- Download the client installation package
-
Execute the installer, select the default value as prompted, and complete the installation. If the installation is blocked, you can right-click or ctrl-click on the installation package and select
Open
. -
configure 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.
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
- MacOS
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
taos> show databases;
name |
=================================
information_schema |
performance_schema |
db |
Query OK, 3 rows in database (0.019154s)
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:
taos> show databases;
name |
=================================
information_schema |
performance_schema |
test |
Query OK, 3 rows in database (0.123000s)
taos>
Execute TDengine CLI program taos
directly from the macOS shell to connect to the TDengine service and enter the TDengine CLI interface, as shown in the following example.
$ taos
taos> show databases;
name |
=================================
information_schema |
performance_schema |
db |
Query OK, 3 rows in database (0.019154s)
taos>
Install Client Library
- 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>3.3.3</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/v3 latest
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 taos
dependency in Cargo.toml
.
[dependencies]
taos = { version = "*"}
Rust client library uses different features to distinguish the way to establish connection. To establish Websocket connection, please enable ws
feature.
taos = { version = "*", default-features = false, features = ["ws"] }
Node.js client library provides different ways of establishing connections by providing different packages.
- Install Node.js Native Client Library
npm install @tdengine/client
It's recommend to use Node whose version is between node-v12.8.0
and node-v13.0.0
.
- Install Node.js REST Client Library
npm install @tdengine/rest
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="3.1.0" />
</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 client library 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.
**Non-Swoole Environment: **
phpize && ./configure && make -j && make install
**Specify TDengine Location: **
phpize && ./configure --with-tdengine-dir=/usr/local/Cellar/tdengine/3.0.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 a 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
- 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 {
// ANCHOR: main
public static void main(String[] args) throws Exception {
// use
// String jdbcUrl =
// "jdbc:TAOS://localhost:6030/dbName?user=root&password=taosdata";
// if you want to connect a specified database named "dbName".
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");
try (Connection conn = DriverManager.getConnection(jdbcUrl, connProps)) {
System.out.println("Connected to " + jdbcUrl + " successfully.");
// you can use the connection for execute SQL here
} catch (Exception ex) {
// please refer to the JDBC specifications for detailed exceptions info
System.out.printf("Failed to connect to %s, %sErrMessage: %s%n",
jdbcUrl,
ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "",
ex.getMessage());
// Print stack trace for context in examples. Use logging in production.
ex.printStackTrace();
throw ex;
}
}
// ANCHOR_END: main
}
public static void main(String[] args) throws Exception {
String jdbcUrl = "jdbc:TAOS-RS://localhost:6041?user=root&password=taosdata";
try (Connection conn = DriverManager.getConnection(jdbcUrl)) {
System.out.println("Connected to " + jdbcUrl + " successfully.");
// you can use the connection for execute SQL here
} catch (Exception ex) {
// please refer to the JDBC specifications for detailed exceptions info
System.out.printf("Failed to connect to %s, %sErrMessage: %s%n",
jdbcUrl,
ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "",
ex.getMessage());
// Print stack trace for context in examples. Use logging in production.
ex.printStackTrace();
throw ex;
}
}
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 Exception {
// use
// String jdbcUrl =
// "jdbc:TAOS-WS://localhost:6041/dbName?user=root&password=taosdata";
// if you want to connect a specified database named "dbName".
String jdbcUrl = "jdbc:TAOS-WS://localhost:6041?user=root&password=taosdata";
Properties connProps = new Properties();
connProps.setProperty(TSDBDriver.PROPERTY_KEY_ENABLE_AUTO_RECONNECT, "true");
connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
try (Connection conn = DriverManager.getConnection(jdbcUrl, connProps)) {
System.out.println("Connected to " + jdbcUrl + " successfully.");
// you can use the connection for execute SQL here
} catch (Exception ex) {
// please refer to the JDBC specifications for detailed exceptions info
System.out.printf("Failed to connect to %s, %sErrMessage: %s%n",
jdbcUrl,
ex instanceof SQLException ? "ErrCode: " + ((SQLException) ex).getErrorCode() + ", " : "",
ex.getMessage());
// Print stack trace for context in examples. Use logging in production.
ex.printStackTrace();
throw ex;
}
}
More configuration about connection, please refer to Java Client Library
import taos
def create_connection():
# all parameters are optional.
conn = None
host = "localhost"
port = 6030
try:
conn = taos.connect(
user="root",
password="taosdata",
host=host,
port=port,
)
print(f"Connected to {host}:{port} successfully.");
except Exception as err:
print(f"Failed to connect to {host}:{port} , ErrMessage:{err}")
raise err
finally:
if conn:
conn.close()
if __name__ == "__main__":
create_connection()
Unified Database Access Interface
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/taosdata/driver-go/v3/taosSql"
)
func main() {
// use
// var taosDSN = "root:taosdata@tcp(localhost:6030)/dbName"
// if you want to connect a specified database named "dbName".
var taosDSN = "root:taosdata@tcp(localhost:6030)/"
taos, err := sql.Open("taosSql", taosDSN)
if err != nil {
log.Fatalln("Failed to connect to " + taosDSN + "; ErrMessage: " + err.Error())
}
fmt.Println("Connected to " + taosDSN + " successfully.")
defer taos.Close()
}
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/taosdata/driver-go/v3/taosRestful"
)
func main() {
// use
// var taosDSN = "root:taosdata@http(localhost:6041)/dbName"
// if you want to connect a specified database named "dbName".
var taosDSN = "root:taosdata@http(localhost:6041)/"
taos, err := sql.Open("taosRestful", taosDSN)
if err != nil {
log.Fatalln("Failed to connect to " + taosDSN + "; ErrMessage: " + err.Error())
}
fmt.Println("Connected to " + taosDSN + " successfully.")
defer taos.Close()
}
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"
"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() -> anyhow::Result<()> {
let dsn = "taos://localhost:6030".to_string();
match TaosBuilder::from_dsn(&dsn)?.build().await {
Ok(_taos) => {
println!("Connected to {} successfully.", dsn);
Ok(())
}
Err(err) => {
eprintln!("Failed to connect to {}, ErrMessage: {}", dsn, err);
return Err(err.into());
}
}
}
For Rust client library, the connection depends on the feature being used. If "ws" feature is enabled, then only the implementation for "websocket" is compiled and packaged.
//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 TDengine.Driver;
using TDengine.Driver.Client;
namespace TDengineExample
{
internal class ConnectExample
{
// ANCHOR: main
static void Main(String[] args)
{
var connectionString = "host=127.0.0.1;port=6030;username=root;password=taosdata";
try
{
// Connect to TDengine server using Native
var builder = new ConnectionStringBuilder(connectionString);
// Open connection with using block, it will close the connection automatically
using (var client = DbDriver.Open(builder))
{
Console.WriteLine("Connected to " + connectionString + " successfully.");
}
}
catch (TDengineError e)
{
// handle TDengine error
Console.WriteLine("Failed to connect to " + connectionString + "; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
throw;
}
catch (Exception e)
{
// handle other exceptions
Console.WriteLine("Failed to connect to " + connectionString + "; Err:" + e.Message);
throw;
}
}
// ANCHOR_END: main
}
}
using System;
using TDengine.Driver;
using TDengine.Driver.Client;
namespace Examples
{
public class WSConnExample
{
// ANCHOR: main
static void Main(string[] args)
{
var connectionString =
"protocol=WebSocket;host=localhost;port=6041;useSSL=false;username=root;password=taosdata";
try
{
// Connect to TDengine server using WebSocket
var builder = new ConnectionStringBuilder(connectionString);
// Open connection with using block, it will close the connection automatically
using (var client = DbDriver.Open(builder))
{
Console.WriteLine("Connected to " + connectionString + " successfully.");
}
}
catch (TDengineError e)
{
// handle TDengine error
Console.WriteLine("Failed to connect to " + connectionString + "; ErrCode:" + e.Code +
"; ErrMessage: " + e.Error);
throw;
}
catch (Exception e)
{
// handle other exceptions
Console.WriteLine("Failed to connect to " + connectionString + "; Err:" + e.Message);
throw;
}
}
// ANCHOR_END: main
}
}
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";
const char *db = NULL; // if don't want to connect to a default db, set it to NULL or ""
uint16_t port = 6030; // 0 means use the default port
TAOS *taos = taos_connect(host, user, passwd, db, port);
if (taos == NULL) {
fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL));
taos_cleanup();
return -1;
}
fprintf(stdout, "Connected to %s:%hu successfully.\n", host, port);
/* put your code here for read and write */
// close & clean
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;
}
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.