Connecting to TDengine
TDengine provides a rich set of application development interfaces. To facilitate users in quickly developing their applications, TDengine supports connectors for multiple programming languages. The official connectors include support for C/C++, Java, Python, Go, Node.js, C#, Rust, Lua (community contribution), and PHP (community contribution). These connectors support connecting to the TDengine cluster using the native interface (taosc) and REST interface (not supported in some languages yet). Community developers have also contributed several unofficial connectors, such as 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:
- Direct connection between the client driver taosc and the server program taosd, referred to as "native connection" in the text below.
- Connection to taosd through the REST API provided by the taosAdapter component, referred to as "REST connection" in the text below.
- Connection to taosd through the WebSocket API provided by the taosAdapter component, referred to as "WebSocket connection" in the text below.
Regardless of the method used to establish the connection, the connectors provide the same or similar API to operate the database and can execute SQL statements. The initialization of the connection slightly differs, but users will not feel any difference in usage. For various connection methods and language connector support, please refer to: Connector Features
Key differences include:
- Using native connection requires ensuring that the client driver taosc and the server's TDengine version are compatible.
- Using REST connection does not require installing the client driver taosc, offering the advantage of cross-platform ease of use, but it lacks features like data subscription and binary data types. Additionally, compared to native and WebSocket connections, the performance of REST connections is the lowest. REST interfaces are stateless. When using REST connections, it is necessary to specify the database names of tables and supertables in SQL.
- Using WebSocket connection also does not require installing the client driver taosc.
- Connecting to cloud service instances must use REST connection or WebSocket connection.
WebSocket connection is recommended
Installing the Client Driver taosc
If you choose a native connection and your application is not running on the same server as TDengine, you need to install the client driver first; otherwise, you can skip this step. To avoid incompatibility between the client driver and the server, please use consistent versions.
Installation Steps
- Linux
- Windows
- macOS
- Download the client installation package
-
Unzip the software package
Place the package in any directory where the current user has read and write access, then execute the following command:
tar -xzvf TDengine-client-VERSION.tar.gz
Replace VERSION with the actual version string. -
Run the installation script
After unzipping the package, you will see the following files (directories) in the unzipped directory:
- install_client.sh: Installation script, used for applying the driver
- package.tar.gz: Application driver installation package
- driver: TDengine application driver
- examples: Sample programs for various programming languages (c/C#/go/JDBC/MATLAB/python/R) Run install_client.sh to install.
-
Configure taos.cfg
Edit the
taos.cfg
file (default path /etc/taos/taos.cfg), changefirstEP
to the End Point of the TDengine server, for example:h1.tdengine.com:6030
- If the TDengine service is not deployed on this machine and only the application driver is installed, then only
firstEP
needs to be configured intaos.cfg
, there is no need to configureFQDN
on this machine. - To prevent the "Unable to resolve FQDN" error when connecting to the server, it is recommended to ensure that the
/etc/hosts
file on your machine is configured with the correct FQDN value of the server, or that the DNS service is 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, follow the prompts to select the default values, 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 that provides RESTful services and accepts write requests from various other software
- taosBenchmark.exe: TDengine test program
- cfg: Configuration file directory
- driver: Application driver dynamic link library
- examples: Example programs for bash/C/C#/go/JDBC/Python/Node.js
- include: Header files
- log: Log files
- unins000.exe: Uninstallation program
-
Configure taos.cfg
Edit the taos.cfg file (default path C:\TDengine\cfg\taos.cfg), change firstEP to the End Point of the TDengine server, for example:
h1.tdengine.com:6030
.
- If using FQDN to connect to the server, ensure that the local network environment DNS is properly configured, or add FQDN addressing records in the hosts file, such as editing C:\Windows\system32\drivers\etc\hosts, adding records like:
192.168.1.99 h1.taos.com
- Uninstallation: 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 installer and follow the prompts to select the default values to complete the installation. If the installation is blocked, you can right-click or press Ctrl and click on the installation package, then choose
Open
. -
Configure taos.cfg
Edit the
taos.cfg
file (default path /etc/taos/taos.cfg), and changefirstEP
to the End Point of the TDengine server, for example:h1.tdengine.com:6030
- If the TDengine service is not deployed on the local machine and only the application driver is installed, then only
firstEP
needs to be configured intaos.cfg
, there is no need to configureFQDN
on the local machine. - To prevent the “Unable to resolve FQDN” error when connecting to the server, it is recommended to ensure that the local
/etc/hosts
file has been configured with the correct FQDN value of the server, or that the DNS service has been properly set up.
Installation Verification
After completing the above installation and configuration, and confirming that the TDengine service has started running normally, you can log in using the TDengine command-line program taos
included in the installation package.
- Linux
- Windows
- macOS
In the Linux shell, execute taos
directly to connect to the TDengine service, entering the TDengine CLI interface, as shown below:
$ 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 directly execute taos.exe
to connect to the TDengine service, entering the TDengine CLI interface. An example is shown below:
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, execute taos
directly to connect to the TDengine service, entering the TDengine CLI interface, as shown below:
$ taos
taos> show databases;
name |
=================================
information_schema |
performance_schema |
db |
Query OK, 3 rows in database (0.019154s)
taos>
Installing Connectors
- Java
- Python
- Go
- Rust
- Node.js
- C#
- C
- REST API
If you are using Maven to manage your project, simply add the following dependency to your pom.xml.
<dependency>
<groupId>com.taosdata.jdbc</groupId>
<artifactId>taos-jdbcdriver</artifactId>
<version>3.4.0</version>
</dependency>
-
Pre-installation Preparation
- Install Python. Recent versions of the taospy package require Python 3.6.2+. Earlier versions of the taospy package require Python 3.7+. The taos-ws-py package requires Python 3.7+. If Python is not already installed on your system, refer to Python BeginnersGuide for installation.
- Install pip. In most cases, the Python installation package comes with the pip tool; if not, refer to the pip documentation for installation.
- If using a native connection, you also need to install the client driver. The client software package includes the TDengine client dynamic link library (libtaos.so or taos.dll) and TDengine CLI.
-
Using pip to Install
- Uninstall old versions If you have previously installed old versions of the Python connector, please uninstall them 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
Note: This package is for native connection
-
Install
taos-ws-py
pip3 install taos-ws-py
Note: This package is for WebSocket connection
- Install both
taospy
andtaos-ws-py
pip3 install taospy[ws]
-
Installation Verification
- Native Connection
- REST Connection
- WebSocket Connection
For native connections, it is necessary to verify that both the client driver and the Python connector itself are correctly installed. If the taos
module can be successfully imported, then the client driver and Python connector are correctly installed. You can enter in the Python interactive Shell:
import taos
For REST connections, you only need to verify if the taosrest
module can be successfully imported. You can enter in the Python interactive Shell:
import taosrest
For WebSocket connections, you only need to verify if the taosws
module can be successfully imported. You can enter 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, make sure GCC is installed on your system.
Edit Cargo.toml
to add the taos
dependency.
[dependencies]
taos = { version = "*"}
The Rust connector distinguishes different connection methods through different features. It supports both native and WebSocket connections by default. If only a WebSocket connection is needed, set the ws
feature:
taos = { version = "*", default-features = false, features = ["ws"] }
-
Pre-installation Preparation
- Install the Node.js development environment, using version 14 or above. Download link: [https://nodejs.org/en/download/](https://nodejs.org/en/download/)
-
Installation
- Use npm to install the Node.js connector
npm install @tdengine/websocket
Note: Node.js currently only supports WebSocket connections
-
Installation Verification
- Create a verification directory, for example:
~/tdengine-test
, download the nodejsChecker.js source code from GitHub to local. - Execute the following commands in the command line.
npm init -y
npm install @tdengine/websocket
node nodejsChecker.js- After performing the above steps, the command line will output the results of nodeChecker.js connecting to the TDengine instance and performing simple insertion and query operations.
- Create a verification directory, for example:
Edit the project configuration file to add a reference to 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.1.0" />
</ItemGroup>
</Project>
You can also add it via the dotnet command:
dotnet add package TDengine.Connector
The following example code is based on dotnet6.0. If you are using another version, 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.
To access TDengine using the REST API method, no drivers or connectors need to be installed.
Establishing Connection
Before proceeding with this step, please ensure that there is a running TDengine that can be accessed, and that the server's FQDN is configured correctly. The following example code assumes that TDengine is installed on the local machine, and that the FQDN (default localhost) and serverPort (default 6030) are using the default configuration.
Connection Parameters
There are many configuration options for connecting, so before establishing a connection, let's first introduce the parameters used by the connectors of each language to establish a connection.
- Java
- Python
- Go
- Rust
- Node.js
- C#
- C
- REST API
The parameters for establishing a connection with the Java connector are URL and Properties.
The JDBC URL format for TDengine is: jdbc:[TAOS|TAOS-WS|TAOS-RS]://[host_name]:[port]/[database_name]?[user={user}|&password={password}|&charset={charset}|&cfgdir={config_dir}|&locale={locale}|&timezone={timezone}|&batchfetch={batchfetch}]
For detailed explanations of URL and Properties parameters and how to use them, see URL specifications
The Python connector uses the connect()
method to establish a connection, here are the specific parameters for the connection:
- url: URL of the
taosAdapter
REST service. The default is port6041
onlocalhost
. - user: TDengine username. The default is
root
. - password: TDengine user password. The default is
taosdata
. - timeout: HTTP request timeout in seconds. The default is
socket._GLOBAL_DEFAULT_TIMEOUT
. Generally, no configuration is needed.
The data source name has a generic format, similar to PEAR DB, but without the type prefix (brackets indicate optional):
[username[:password]@][protocol[(address)]]/[dbname][?param1=value1&...¶mN=valueN]
Complete DSN format:
username:password@protocol(address)/dbname?param=value
Supported DSN parameters are as follows:
Native connection:
cfg
specifies the taos.cfg directorycgoThread
specifies the number of cgo operations that can be executed concurrently, default is the number of system corescgoAsyncHandlerPoolSize
specifies the size of the async function handler, default is 10000
REST connection:
disableCompression
whether to accept compressed data, default is true which means not accepting compressed data, set to false if data transmission uses gzip compression.readBufferSize
the size of the buffer for reading data, default is 4K (4096), this value can be increased appropriately when the query result data volume is large.token
the token used when connecting to cloud services.skipVerify
whether to skip certificate verification, default is false which means not skipping certificate verification, set to true if connecting to an insecure service.
WebSocket connection:
enableCompression
whether to send compressed data, default is false which means not sending compressed data, set to true if data transmission uses compression.readTimeout
the timeout for reading data, default is 5m.writeTimeout
the timeout for writing data, default is 10s.
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 explanation of DSN and how to use it, see Connection Features
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: Username and password for the database.
-
host/port: Host address and port number. For example,
localhost:6041
-
database: Database name.
-
params: Other parameters. For example, token.
-
Complete DSN example:
ws://root:taosdata@localhost:6041
ConnectionStringBuilder uses a key-value pair method to set connection parameters, where key is the parameter name and value is the parameter value, separated by a semicolon ;
.
For example:
"protocol=WebSocket;host=127.0.0.1;port=6041;useSSL=false"
Supported parameters are as follows:
host
: The address of the TDengine instance.port
: The port of the TDengine instance.username
: Username for the connection.password
: Password for the connection.protocol
: Connection protocol, options are Native or WebSocket, default is Native.db
: Database to connect to.timezone
: Time zone, default is the local time zone.connTimeout
: Connection timeout, default is 1 minute.
Additional parameters supported for WebSocket connections:
readTimeout
: Read timeout, default is 5 minutes.writeTimeout
: Send timeout, default is 10 seconds.token
: Token for connecting to TDengine cloud.useSSL
: Whether to use SSL connection, default is false.enableCompression
: Whether to enable WebSocket compression, default is false.autoReconnect
: Whether to automatically reconnect, default is false.reconnectRetryCount
: Number of retries for reconnection, default is 3.reconnectIntervalMs
: Reconnection interval in milliseconds, default is 2000.
WebSocket Connection
For C/C++ language connectors, the WebSocket connection uses the ws_connect()
function to establish a connection with the TDengine database. Its parameter is a DSN description string, structured as follows:
<driver>[+<protocol>]://[[<username>:<password>@]<host>:<port>][/<database>][?<p1>=<v1>[&<p2>=<v2>]]
|------|------------|---|-----------|-----------|------|------|------------|-----------------------|
|driver| protocol | | username | password | host | port | database | params |
For detailed explanation of DSN and how to use it, see Connection Features
Native Connection
For C/C++ language connectors, the native connection method uses the taos_connect()
function to establish a connection with the TDengine database. Detailed parameters are as follows:
host
: Hostname or IP address of the database server to connect to. If it is a local database,"localhost"
can be used.user
: Username for logging into the database.passwd
: Password corresponding to the username.db
: Default database name when connecting. If no database is specified, passNULL
or an empty string.port
: Port number the database server listens on. The default port number is6030
.
The taos_connect_auth()
function is also provided for establishing a connection with the TDengine database using an MD5 encrypted password. This function is similar to taos_connect
, but differs in the handling of the password, as taos_connect_auth
requires the MD5 encrypted string of the password.
When accessing TDengine via REST API, the application directly establishes an HTTP connection with taosAdapter, and it is recommended to use a connection pool to manage connections.
For specific parameters using the REST API, refer to: HTTP request format
WebSocket Connection
Below are code examples for establishing WebSocket connections in various language connectors. It demonstrates how to connect to the TDengine database using WebSocket and set some parameters for the connection. The whole 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 examples of code for establishing native connections in various languages. It demonstrates how to connect to the TDengine database using a native connection method and set some parameters for the connection. The entire process mainly involves establishing a 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 examples of code for establishing REST connections in various languages. It demonstrates how to connect to the TDengine database using a REST connection method. The entire process mainly involves establishing a 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
Access TDengine using the REST API method, where the application independently establishes an HTTP connection.
If the connection fails, in most cases it is due to incorrect FQDN or firewall settings. For detailed troubleshooting methods, please see "Encountering the error 'Unable to establish connection, what should I do?'" in the "Common Questions and Feedback".
Connection Pool
Some connectors offer a connection pool, or can be used in conjunction with existing connection pool components. By using a connection pool, applications can quickly obtain available connections from the pool, avoiding the overhead of creating and destroying connections with each operation. This not only reduces resource consumption but also improves response speed. Additionally, connection pools support the management of connections, such as limiting the maximum number of connections and checking the validity of connections, ensuring efficient and reliable use of connections. We recommend managing connections using a connection pool.
Below are code examples of connection pool support for various language connectors.
- Java
- Python
- Go
- Rust
HikariCP
Example usage is as follows:
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 through HikariDataSource.getConnection(), you need to call the close() method after use, which actually does not close the connection but returns it to the pool. For more issues about using HikariCP, please see the official documentation.
Druid
Example usage is as follows:
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 about using Druid, please see 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
creates a connection that has already implemented a connection pool, and you can set connection pool parameters through the API, as shown in the example 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 connection pooling. The connection pool for [taos] by default (in asynchronous mode) is implemented using [deadpool].
Below, you can create a connection pool with default parameters.
let pool: Pool<TaosBuilder> = TaosBuilder::from_dsn("taos:///")
.unwrap()
.pool()
.unwrap();
You can also use the connection pool builder to set the 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 your application code, use pool.get()?
to obtain a connection object [Taos].
let taos = pool.get()?;