Connecting to TDengine
TDengine provides a rich set of application development interfaces. To facilitate users in quickly developing their applications, TDengine supports various programming language connectors, including official connectors for C/C++, Java, Python, Go, Node.js, C#, Rust, Lua (community-contributed), and PHP (community-contributed). These connectors support connecting to TDengine clusters using native interfaces (taosc) and REST interfaces (not supported by some languages). Community developers have also contributed several unofficial connectors, such as the ADO.NET connector, Lua connector, and PHP connector. Additionally, TDengine can directly call the REST API provided by taosadapter for data writing and querying operations.
Connection Methods
TDengine provides three methods for establishing connections:
- Directly connect to the server program taosd using the client driver taosc; this method is referred to as "native connection."
- Establish a connection to taosd via the REST API provided by the taosAdapter component; this method is referred to as "REST connection."
- Establish a connection to taosd via the WebSocket API provided by the taosAdapter component; this method is referred to as "WebSocket connection."
Regardless of the method used to establish a connection, the connectors provide similar API operations for databases and can execute SQL statements. The only difference lies in how the connection is initialized, and users should not notice any difference in usage. For various connection methods and language connector support, refer to: Feature Support.
Key differences include:
- For the native connection, it is necessary to ensure that the client driver taosc and the TDengine server version are compatible.
- With the REST connection, users do not need to install the client driver taosc, which offers cross-platform ease of use; however, users cannot experience features like data subscription and binary data types. Moreover, REST connections have the lowest performance compared to native and WebSocket connections. The REST API is stateless, and when using REST connections, users must specify the database name for tables and supertables in SQL.
- For the WebSocket connection, users also do not need to install the client driver taosc.
- To connect to cloud service instances, users must use REST or WebSocket connections.
It is recommended to use WebSocket connections.
Install the Client Driver taosc
If you choose the native connection and the application is not running on the same server as TDengine, you need to install the client driver first; otherwise, this step can be skipped. To avoid incompatibility between the client driver and server, please use the same version.
Installation Steps
- Linux
- Windows
- macOS
- Download the client installation package
-
Extract the software package
Place the package in any directory where the current user has read and write permissions, then execute the following command:
tar -xzvf TDengine-client-VERSION.tar.gz
ReplaceVERSION
with the actual version string. -
Execute the installation script
After extracting the package, you will see the following files (directories) in the extraction directory:
- install_client.sh: The installation script for the application driver
- package.tar.gz: The application driver installation package
- driver: The TDengine application driver
- examples: Example programs in various programming languages (C/C#/Go/JDBC/MATLAB/Python/R)
Run
install_client.sh
to perform the installation.
-
Configure
taos.cfg
Edit the
taos.cfg
file (default path:/etc/taos/taos.cfg
) and changefirstEP
to the TDengine server's End Point, for example:h1.tdengine.com:6030
- If TDengine service is not deployed on this machine and only the application driver is installed, you only need to configure
firstEP
intaos.cfg
, and there is no need to configureFQDN
on this machine. - To prevent the error "Unable to resolve FQDN" when connecting to the server, it is recommended to ensure that the
/etc/hosts
file on this machine has been configured with the correct FQDN value for the server or that DNS services have been properly 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. -
Run the installer, choose the default options as prompted, and complete the installation.
-
Installation Path
The default installation path is:
C:\TDengine
, which includes the following files (directories):- taos.exe: TDengine CLI command-line program
- taosadapter.exe: Server executable file providing RESTful services and accepting write requests from various other software
- taosBenchmark.exe: TDengine testing program
- cfg: Configuration file directory
- driver: Application driver dynamic link library
- examples: Example programs in bash/C/C#/go/JDBC/Python/Node.js
- include: Header files
- log: Log files
- unins000.exe: Uninstaller
-
Configure
taos.cfg
Edit the
taos.cfg
file (default pathC:\TDengine\cfg\taos.cfg
) and changefirstEP
to the TDengine server's endpoint, for example:h1.tdengine.com:6030
.
- If connecting to the server using FQDN, ensure that the local network environment's DNS is configured, or add an FQDN addressing record in the hosts file, such as editing
C:\Windows\system32\drivers\etc\hosts
to add a record like:192.168.1.99 h1.taos.com
. - Uninstall: Run
unins000.exe
to uninstall the TDengine application driver.
-
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. -
Run the installation program and follow the prompts to choose the default values to complete the installation. If the installation is blocked, you can right-click or press Ctrl while clicking the installation package and select
Open
. -
Configure
taos.cfg
Edit the
taos.cfg
file (default path:/etc/taos/taos.cfg
) and changefirstEP
to the TDengine server's End Point, for example:h1.tdengine.com:6030
- If TDengine service is not deployed on this machine and only the application driver is installed, you only need to configure
firstEP
intaos.cfg
, and there is no need to configureFQDN
on this machine. - To prevent the error "Unable to resolve FQDN" when connecting to the server, it is recommended to ensure that the
/etc/hosts
file on this machine has been configured with the correct FQDN value for the server or that DNS services have been properly configured.
Installation Verification
After the installation and configuration are complete, and ensuring that the TDengine service is running normally, you can execute the TDengine command-line program taos included in the installation package to log in.
- Linux
- Windows
- macOS
In the Linux shell, you can directly execute taos
to connect to the TDengine service and enter the TDengine CLI interface. Here is an example:
$ taos
taos> show databases;
name |
=================================
information_schema |
performance_schema |
db |
Query OK, 3 rows in database (0.019154s)
taos>
In the CMD, navigate to the C:\TDengine
directory and execute taos.exe
to connect to the TDengine service, entering the TDengine CLI interface. Here is an example:
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>
In the macOS shell, you can directly execute taos
to connect to the TDengine service and enter the TDengine CLI interface. Here is an 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#
- C
- REST API
If you are using Maven to manage the project, simply add the following dependency to the pom.xml.
<dependency>
<groupId>com.taosdata.jdbc</groupId>
<artifactId>taos-jdbcdriver</artifactId>
<version>3.4.0</version>
</dependency>
- Installation Prerequisites
- Install Python. The latest version of the taospy package requires Python 3.6.2+. Earlier versions require Python 3.7+. The taos-ws-py package requires Python 3.7+. If Python is not already installed on your system, refer to the Python BeginnersGuide for installation.
- Install pip. Most Python installation packages come with the pip tool. If not, refer to the pip documentation for installation.
- If you are using the native connection, you also need to install the client driver. The client software includes the TDengine client dynamic link library (libtaos.so or taos.dll) and the TDengine CLI.
- Install using pip
-
Uninstall old versions If you previously installed an older version of the Python connector, please uninstall it first.
pip3 uninstall taos taospy
pip3 uninstall taos taos-ws-py- Install
taospy
-
Latest version
pip3 install taospy
-
Install a specific version
pip3 install taospy==2.3.0
-
Install from GitHub
pip3 install git+https://github.com/taosdata/taos-connector-python.git
-
This installation package is for the native connector.-
Install
taos-ws-py
pip3 install taos-ws-py
This installation package is for the WebSocket connector.-
Install both
taospy
andtaos-ws-py
pip3 install taospy[ws]
- Install
-
- Installation Verification
- Native Connection
- REST Connection
- WebSocket Connection
For the native connection, verify that both the client driver and the Python connector are correctly installed. If you can successfully import the taos
module, it indicates that the client driver and Python connector have been correctly installed. You can type the following in the Python interactive shell:
import taos
For the REST connection, you only need to verify whether you can successfully import the taosrest
module. You can type the following in the Python interactive shell:
import taosrest
For the WebSocket connection, you only need to verify whether you can successfully import the taosws
module. You can type the following in the Python interactive shell:
import taosws
Edit go.mod
to add the driver-go
dependency.
module goexample
go 1.17
require github.com/taosdata/driver-go/v3 latest
driver-go uses cgo to wrap the taosc API. cgo requires GCC to compile C source code. Therefore, ensure that your system has GCC installed.
Edit Cargo.toml
to add the taos
dependency.
[dependencies]
taos = { version = "*"}
The Rust connector differentiates between connection methods through different features. By default, it supports both native and WebSocket connections. If you only need to establish a WebSocket connection, you can set the ws
feature:
taos = { version = "*", default-features = false, features = ["ws"] }
-
Installation Prerequisites
- Install the Node.js development environment, using version 14 or higher. Download link
-
Installation
-
Install the Node.js connector using npm
npm install @tdengine/websocket
Node.js currently only supports WebSocket connections. -
-
Installation Verification
-
Create an installation verification directory, for example:
~/tdengine-test
, and download the nodejsChecker.js source code from GitHub to your local machine. -
Execute the following command in the terminal.
npm init -y
npm install @tdengine/websocket
node nodejsChecker.js -
After executing the above steps, the command line will output the results of connecting to the TDengine instance and performing a simple insert and query.
-
Add the reference for 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>
You can also add it using the dotnet command:
dotnet add package TDengine.Connector
The following example code is based on dotnet 6.0; if you are using other versions, you may need to make appropriate adjustments.
If you have already installed the TDengine server software or the TDengine client driver taosc, then the C connector is already installed, and no additional action is required.
Using the REST API to access TDengine does not require the installation of any drivers or connectors.
Establishing Connections
Before executing this step, ensure that there is a running and accessible TDengine instance, and that the server's FQDN is configured correctly. The following example code assumes that TDengine is installed on the local machine, with the FQDN (default localhost) and serverPort (default 6030) using default configurations.
Connection Parameters
There are many configuration items for the connection. Before establishing the connection, we can introduce the parameters used by each language connector to establish a connection.
- Java
- Python
- Go
- Rust
- Node.js
- C#
- C
- REST API
The parameters for establishing a connection with the Java connector include URL and Properties.
The standard format for TDengine's JDBC URL is: jdbc:[TAOS|TAOS-RS]://[host_name]:[port]/[database_name]?[user={user}|&password={password}|&charset={charset}|&cfgdir={config_dir}|&locale={locale}|&timezone={timezone}|&batchfetch={batchfetch}]
For detailed parameter descriptions of URL and Properties, and how to use them, refer to URL Specification.
Note: Adding the batchfetch
parameter and setting it to true in REST connections will enable the WebSocket connection.
The Python connector uses the connect()
method to establish a connection. The specific descriptions of the connection parameters are as follows:
- url: The URL of the
taosAdapter
REST service. The default is port6041
onlocalhost
. - user: The TDengine username. The default is
root
. - password: The TDengine user password. The default is
taosdata
. - timeout: The HTTP request timeout, in seconds. The default is
socket._GLOBAL_DEFAULT_TIMEOUT
, which usually does not need to be configured.
The data source name has a general format, such as PEAR DB, but without a type prefix (the brackets indicate that it is optional):
[username[:password]@][protocol[(address)]]/[dbname][?param1=value1&...¶mN=valueN]
The complete form of the DSN:
username:password@protocol(address)/dbname?param=value
Supported DSN parameters include:
For native connections:
cfg
: Specifies the taos.cfg directory.cgoThread
: Specifies the number of cgo threads to execute concurrently, defaulting to the number of system cores.cgoAsyncHandlerPoolSize
: Specifies the size of the async function handler, defaulting to 10,000.
For REST connections:
disableCompression
: Whether to accept compressed data; default is true (does not accept compressed data). If using gzip compression for transmission, set to false.readBufferSize
: The size of the read data buffer, defaulting to 4K (4096). This value can be increased for larger query results.token
: The token used when connecting to cloud services.skipVerify
: Whether to skip certificate verification; default is false (does not skip verification). Set to true if connecting to an insecure service.
For WebSocket connections:
enableCompression
: Whether to send compressed data; default is false (does not send compressed data). Set to true if using compression.readTimeout
: The read timeout for data, defaulting to 5m.writeTimeout
: The write timeout for data, defaulting to 10s.
The Rust connector uses DSN to create connections. The basic structure of the DSN description string is as follows:
<driver>[+<protocol>]://[[<username>:<password>@]<host>:<port>][/<database>][?<p1>=<v1>[&<p2>=<v2>]]
|------|------------|---|-----------|-----------|------|------|------------|-----------------------|
|driver| protocol | | username | password | host | port | database | params |
For detailed DSN explanations and usage, refer to Connection Functionality.
The Node.js connector uses DSN to create connections. The basic structure of the DSN description string is as follows:
[+<protocol>]://[[<username>:<password>@]<host>:<port>][/<database>][?<p1>=<v1>[&<p2>=<v2>]]
|------------|---|-----------|-----------|------|------|------------|-----------------------|
| protocol | | username | password | host | port | database | params |
-
protocol: Establish a connection using the WebSocket protocol. For example,
ws://localhost:6041
. -
username/password: The database username and password.
-
host/port: The host address and port number. For example,
localhost:6041
. -
database: The database name.
-
params: Other parameters, such as token.
-
Complete DSN example:
ws://root:taosdata@localhost:6041
The ConnectionStringBuilder sets connection parameters using a key-value approach, where the key is the parameter name and the value is the parameter value, separated by semicolons ;
.
For example:
"protocol=WebSocket;host=127.0.0.1;port=6041;useSSL=false"
Supported parameters include:
host
: The address of the TDengine instance.port
: The port of the TDengine instance.username
: The username for the connection.password
: The password for the connection.protocol
: The connection protocol, with optional values of Native or WebSocket, defaulting to Native.db
: The connected database.timezone
: The timezone, defaulting to the local timezone.connTimeout
: The connection timeout, defaulting to 1 minute.
WebSocket connections also support the following parameters:
readTimeout
: The read timeout, defaulting to 5 minutes.writeTimeout
: The send timeout, defaulting to 10 seconds.token
: The token for connecting to TDengine cloud.useSSL
: Whether to use SSL for the connection, defaulting to false.enableCompression
: Whether to enable WebSocket compression, defaulting to false.autoReconnect
: Whether to automatically reconnect, defaulting to false.reconnectRetryCount
: The number of reconnection attempts, defaulting to 3.reconnectIntervalMs
: The reconnection interval in milliseconds, defaulting to 2000.
WebSocket Connection
The C/C++ language connector uses the ws_connect()
function to establish a connection to the TDengine database. Its parameter is a DSN description string with the following basic structure:
<driver>[+<protocol>]://[[<username>:<password>@]<host>:<port>][/<database>][?<p1>=<v1>[&<p2>=<v2>]]
|------|------------|---|-----------|-----------|------|------|------------|-----------------------|
|driver| protocol | | username | password | host | port | database | params |
For detailed DSN explanations and usage, refer to DSN.
Native Connection
The C/C++ language connector uses the taos_connect()
function to establish a connection to the TDengine database. The detailed parameter descriptions are as follows:
host
: The hostname or IP address of the database server to connect to. If it is a local database, you can use"localhost"
.user
: The username used to log in to the database.passwd
: The password corresponding to the username.db
: The default database name to select when connecting. If not specified, you can passNULL
or an empty string.port
: The port number that the database server listens on. The default port number is6030
.
There is also the taos_connect_auth()
function for establishing a connection to the TDengine database using an MD5-encrypted password. This function works the same as taos_connect
, but the difference lies in how the password is handled; taos_connect_auth
requires the MD5 hash of the password.
When accessing TDengine via the REST API, the application directly establishes an HTTP connection with taosAdapter. It is recommended to use a connection pool to manage connections.
For specific parameters used in the REST API, refer to: HTTP Request Format.
WebSocket Connection
Below are code samples for establishing a WebSocket connection using each language connector. They demonstrate how to connect to the TDengine database using the WebSocket connection method and set some parameters for the connection. The entire process mainly involves establishing the database connection and handling exceptions.
- Java
- Python
- Go
- Rust
- Node.js
- C#
- C
- REST API
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;
}
}
import taosws
def create_connection():
conn = None
host = "localhost"
port = 6041
try:
conn = taosws.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
return conn
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/taosdata/driver-go/v3/taosWS"
)
func main() {
// use
// var taosDSN = "root:taosdata@ws(localhost:6041)/dbName"
// if you want to connect a specified database named "dbName".
var taosDSN = "root:taosdata@ws(localhost:6041)/"
taos, err := sql.Open("taosWS", taosDSN)
if err != nil {
log.Fatalln("Failed to connect to " + taosDSN + "; ErrMessage: " + err.Error())
}
fmt.Println("Connected to " + taosDSN + " successfully.")
defer taos.Close()
}
use taos::*;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let dsn = "ws://localhost:6041".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());
}
}
}
const taos = require("@tdengine/websocket");
let dsn = 'ws://localhost:6041';
async function createConnect() {
try {
let conf = new taos.WSConfig(dsn);
conf.setUser('root');
conf.setPwd('taosdata');
conf.setDb('power');
conn = await taos.sqlConnect(conf);
console.log("Connected to " + dsn + " successfully.");
return conn;
} catch (err) {
console.log("Failed to connect to " + dsn + ", ErrCode: " + err.code + ", ErrMessage: " + err.message);
throw err;
}
}
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;
}
}
// compile with
// gcc connect_example.c -o connect_example -ltaos
#include <stdio.h>
#include <stdlib.h>
#include "taosws.h"
int main() {
ws_enable_log("debug");
char *dsn = "ws://localhost:6041";
WS_TAOS *taos = ws_connect(dsn);
if (taos == NULL) {
fprintf(stderr, "Failed to connect to %s, ErrCode: 0x%x, ErrMessage: %s.\n", dsn, ws_errno(NULL), ws_errstr(NULL));
return -1;
}
fprintf(stdout, "Connected to %s successfully.\n", dsn);
/* put your code here for read and write */
// close & clean
ws_close(taos);
}
Not supported
Native Connection
Below are code samples for establishing a native connection using each language connector. They demonstrate how to connect to the TDengine database using the native connection method and set some parameters for the connection. The entire process mainly involves establishing the database connection and handling exceptions.
- Java
- Python
- Go
- Rust
- Node.js
- C#
- C
- REST API
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;
}
}
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()
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()
}
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());
}
}
}
Not supported
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;
}
}
// 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();
}
Not supported
REST Connection
Below are code samples for establishing a REST connection using each language connector. They demonstrate how to connect to the TDengine database using the REST connection method. The entire process mainly involves establishing the database connection and handling exceptions.
- Java
- Python
- Go
- Rust
- Node.js
- C#
- C
- REST API
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;
}
}
import taosrest
def create_connection():
conn = None
url="http://localhost:6041"
try:
conn = taosrest.connect(url=url,
user="root",
password="taosdata",
timeout=30)
print(f"Connected to {url} successfully.");
except Exception as err:
print(f"Failed to connect to {url} , ErrMessage:{err}")
finally:
if conn:
conn.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()
}
Not supported
Not supported
Not supported
Not supported
Using the REST API to access TDengine allows the application to independently establish HTTP connections.
If the connection fails, in most cases, it is due to incorrect FQDN or firewall configuration. For detailed troubleshooting methods, refer to Frequently Asked Questions under "If I encounter the error Unable to establish connection, what should I do?"
Connection Pool
Some connectors provide connection pools or can work with existing connection pool components. Using a connection pool allows applications to quickly obtain available connections from the pool, avoiding the overhead of creating and destroying connections for each operation. This not only reduces resource consumption but also improves response speed. Additionally, connection pools support connection management, such as limiting the maximum number of connections and checking connection validity, ensuring efficient and reliable use of connections. We recommend using connection pools to manage connections.
Below are code samples for connection pool support in various language connectors.
- Java
- Python
- Go
- Rust
HikariCP
Usage example:
public static void main(String[] args) throws Exception {
HikariConfig config = new HikariConfig();
// jdbc properties
config.setJdbcUrl("jdbc:TAOS://127.0.0.1:6030/log");
config.setUsername("root");
config.setPassword("taosdata");
// connection pool configurations
config.setMinimumIdle(10); // minimum number of idle connection
config.setMaximumPoolSize(10); // maximum number of connection in the pool
config.setConnectionTimeout(30000); // maximum wait milliseconds for get connection from pool
config.setMaxLifetime(0); // maximum life time for each connection
config.setIdleTimeout(0); // max idle time for recycle idle connection
config.setConnectionTestQuery("SELECT SERVER_VERSION()"); // validation query
HikariDataSource dataSource = new HikariDataSource(config); // create datasource
Connection connection = dataSource.getConnection(); // get connection
Statement statement = connection.createStatement(); // get statement
// query or insert
// ...
statement.close();
connection.close(); // put back to connection pool
dataSource.close();
}
After obtaining a connection via HikariDataSource.getConnection(), you need to call the close() method after use; it does not actually close the connection, but returns it to the pool. For more issues related to HikariCP usage, refer to the official documentation.
Druid
Usage example:
public static void main(String[] args) throws Exception {
String url = "jdbc:TAOS://127.0.0.1:6030/log";
DruidDataSource dataSource = new DruidDataSource();
// jdbc properties
dataSource.setDriverClassName("com.taosdata.jdbc.TSDBDriver");
dataSource.setUrl(url);
dataSource.setUsername("root");
dataSource.setPassword("taosdata");
// pool configurations
dataSource.setInitialSize(10);
dataSource.setMinIdle(10);
dataSource.setMaxActive(10);
dataSource.setMaxWait(30000);
dataSource.setValidationQuery("SELECT SERVER_VERSION()");
Connection connection = dataSource.getConnection(); // get connection
Statement statement = connection.createStatement(); // get statement
// query or insert
// ...
statement.close();
connection.close(); // put back to connection pool
dataSource.close();
}
For more issues related to Druid usage, refer to the official documentation.
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()
Using sql.Open
, the created connection already implements a connection pool. You can set connection pool parameters via the API, as shown below:
// SetMaxOpenConns sets the maximum number of open connections to the database. 0 means unlimited.
taos.SetMaxOpenConns(0)
// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
taos.SetMaxIdleConns(2)
// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
taos.SetConnMaxLifetime(0)
// SetConnMaxIdleTime sets the maximum amount of time a connection may be idle.
taos.SetConnMaxIdleTime(0)
In complex applications, it is recommended to enable the connection pool. The [taos] connection pool, by default (asynchronous mode), uses [deadpool] for implementation.
Here is how to generate a connection pool with default parameters.
let pool: Pool<TaosBuilder> = TaosBuilder::from_dsn("taos:///").unwrap().pool().unwrap();
You can also use the pool constructor to set connection pool parameters:
let pool: Pool<TaosBuilder> = Pool::builder(Manager::from_dsn(self.dsn.clone()).unwrap().0)
.max_size(88) // Maximum number of connections
.build()
.unwrap();
In the application code, use pool.get()?
to obtain a connection object from [Taos].
let taos = pool.get()?;