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 connectors for various programming languages, including C/C++, Java, Python, Go, Node.js, C#, and Rust, to access TDengine. These connectors support connecting to TDengine clusters using both native interfaces (taosc). Some connectors also support connecting over a REST interface. Community developers have also contributed several unofficial connectors, such as the ADO.NET connector, the Lua connector, and the PHP connector.
Establish Connection
There are two ways for a connector to establish connections to TDengine:
- REST connection through the REST API provided by the taosAdapter component.
- Native connection through the TDengine client driver (taosc).
For REST and native connections, connectors 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:
- The REST connection is more accessible with cross-platform support, however it results in a 30% performance downgrade.
- The TDengine client driver (taosc) has the highest performance with all the features of TDengine like Parameter Binding, Subscription, etc.
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
Download TDengine
Enter your email to receive a download link
I would like to receive TDengine news and communications at this address.
Submit
Close
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.
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
tip
- 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 TDengine
Enter your email to receive a download link
I would like to receive TDengine news and communications at this address.
Submit
Close
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 softwares
- 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
.
tip
- 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
Download TDengine
Enter your email to receive a download link
I would like to receive TDengine news and communications at this address.
Submit
Close
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
tip
- 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 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>3.0.0</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
.
go.mod
module goexample
go 1.17
require github.com/taosdata/driver-go/v3 latest
note
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
.
Cargo.toml
[dependencies]
libtaos = { version = "0.4.2"}
info
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 install @tdengine/client
note
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 install @tdengine/rest
Just need to add the reference to TDengine.Connector in the project configuration file.
csharp.csproj
<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>
Or add by dotnet
command.
dotnet add package TDengine.Connector
note
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/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
Native Connection
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".
REST Connection
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.
Enable Bulk Pulling
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
Native Connection
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
Native 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".
REST Connection
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".
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.
Establish native connection using af package
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")
}
}
Native Connection/REST Connection
use taos::*;
#[tokio::main]
async fn main() -> Result<(), Error> {
#[allow(unused_variables)]
let taos = TaosBuilder::from_dsn("taos://")?.build()?;
println!("Connected");
Ok(())
}
note
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.
Native Connection
//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();
REST Connection
const { options, connect } = require("@tdengine/rest");
async function test() {
options.path = "/rest/sql";
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() |
// ===================
// 3.0.0.0 |
Native Connection
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();
}
}
}
WebSocket Connection
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;
}
}
}
Native Connection
library("DBI")
library("rJava")
library("RJDBC")
args<- commandArgs(trailingOnly = TRUE)
driver_path = args[1] # path to jdbc-driver for example: "/root/taos-jdbcdriver-3.0.0-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)
Native Connection
// 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
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.