Establishing a Connection
connect() establishes a connection to a DolphinDB node. You can pass
parameters such as host, port, and login information directly, or manage
connection configuration through ConnectionConfig or a
dictionary.def connect(
self,
host=None,
port=None,
userid=None,
password=None,
*,
config=None,
**kwargs,
) -> bool: ...host and port are required. They can be passed directly or written in config. Login information supports both methods as well. Other connection options can be set through config or keyword arguments.
Each time connect() is explicitly called, the connection options are
reinitialized to their default values and do not inherit settings from the previous
connection. To retain custom configurations such as reconnect, timeout, or
high-availability settings, you must pass them again in each connect()
call.
Basic connection parameters host, port, userid, password
host and port specify the server address and port and are required for
establishing a connection. host can be a domain name, IP address, or host
name. port is the server listening port. They can be passed through
positional arguments, keyword arguments, ConnectionConfig, or a
configuration dictionary. userid and password are optional
credentials. If not specified, the API establishes the connection without logging
in; you can call login() later if authentication is required. In
ConnectionConfig, userId is supported as a
backward-compatible alias for userid.
import dolphindb as ddb
conn = ddb.DBConnection()
conn.connect(
host="localhost",
port=8848,
userid="admin",
password="your_password",
)
Startup script startup
-
startup: optional, str, default "". A DolphinDB script executed immediately after the connection is established (e.g., loading plugins, defining functions, or initializing tables).
Note: The startup script is executed upon initial connection, automatic
reconnection (reconnect=True), and high-availability node
failover/switching. Therefore, the script should be idempotent (e.g., function
definitions or idempotent assignments) to avoid side effects such as data
duplication or unintended counter increments.
import dolphindb as ddb
conn = ddb.DBConnection()
conn.connect("localhost", 8848, startup="x = 1..10")
print(conn.run("sum(x)"))
# output: 55
If no startup script is required, omit startup or pass an empty string.
Explicitly passing startup=None is not recommended.
High availability parameters enable_high_availability, high_availability_sites
-
enable_high_availability: optional, bool, default False. Whether to enable the high availability mode for the API.
-
high_availability_sites: list of strings, optional, default []. A list of available cluster nodes, each in the format of <ip>:<port>.
Enabling high availability automatically enables automatic reconnection. When
establishing a connection, the API first connects to the target node specified in
connect() (or the union of this node and
high_availability_sites, if configured) to retrieve the cluster status.
It then automatically adds available nodes in the cluster to the candidate pool and
prioritizes connecting to a node with lower load.
Note: When connections are created concurrently under high load, they may not be distributed evenly across nodes due to delays in synchronizing load information.
import dolphindb as ddb
sites = ["x.x.x.x:x", "x.x.x.x:x"]
conn = ddb.DBConnection()
conn.connect(
host="x.x.x.x:x",
port=xxx,
userid="admin",
password="your_password",
enable_high_availability=True,
high_availability_sites=sites,
)
In high availability mode, when the server returns a parseable
<NotLeader> response, the API switches to the specified
leader node. If the current node is unavailable, the API tries other available
nodes. If use_public_name is enabled and the cluster provides the
corresponding publicName, the API uses that external address.
Reconnection parameters reconnect, try_reconnect_nums
-
reconnect: optional, bool, default False. Whether to reconnect if the API detects a connection exception when high availability is disabled.
-
try_reconnect_nums: optional, int, default None. Specifies the number of reconnection attempts. If unspecified, or set to 0 or a negative number, it indicates unlimited reconnection attempts. If set to a positive integer, it limits the maximum reconnection attempts in both HA and non-HA modes. In HA mode, each attempt traverses all candidate nodes once, with a maximum of try_reconnect_numsattempts.
startup
script.conn = ddb.DBConnection()
conn.connect(
"localhost",
8848,
reconnect=True,
try_reconnect_nums=5,
)Timeout parameters timeout, net_timeout
-
timeout: optional,
datetime.timedelta, default None. Specifies the timeout for waiting to receive a response from the server. -
net_timeout: optional,
datetime.timedelta, default None. Specifies the timeout for underlying network operations, including TCP connection establishment, data writes, and keep-alive detection.
Note:
-
Neither parameter imposes a strict upper limit on the total duration of an API call (actual elapsed time may be longer if automatic reconnection or multiple network interactions occur).
-
A receive timeout does not cancel jobs already submitted and executing on the server.
from datetime import timedelta
import dolphindb as ddb
conn = ddb.DBConnection()
conn.connect(
host="localhost",
port=8848,
timeout=timedelta(seconds=30),
net_timeout=timedelta(seconds=10),
)
As with other connection settings, each explicit call to connect()
recalculates timeout and net_timeout based on the parameters passed in
the current call, and does not reuse timeout settings from the previous
connection.
Omitting timeout or net_timeout, or passing None, means that the item is unspecified. read_timeout and write_timeout that are passed in the same call remain effective and are not cleared by None.
timedelta(0) is an explicit zero value and is different from None.
It clears the corresponding read_timeout or write_timeout in the same
call. timeout=timedelta(0) means there is no limit on the time
spent waiting for the server response. If net_timeout=timedelta(0)
and keep_alive_time <= 0, this connection still uses the global
default network timeout described below.
If net_timeout is not specified and keep_alive_time <= 0,
the connection uses the global default network timeout, which is currently 3
seconds. You can change it with the following interface:
import dolphindb.global_config as cfg
cfg.tcp.set_timeout(30) # in seconds
cfg.tcp.set_timeout(0) means using the system default network
timeout. Passing a negative value throws ValueError.
DBConnection reads this configuration whenever
connect() is called explicitly and the global default value is
needed. DBConnectionPool reads it during construction. Changing
this configuration does not immediately affect established connections. Automatic
reconnection still reuses the value determined by the connection's last
connect() call, and existing DBConnectionPool
objects retain the value read during construction.
Note:
SimpleDBConnectionPool can set timeout and
net_timeout separately in the pool configuration. Its
acquire(timeout=...) specifies the time to wait for an idle
connection, in milliseconds, and is not the same as the network timeout in this
section. For detailed timeout behavior of connection pools, see the connection pool
constructor.
Timeout and keep-alive parameters keep_alive_time, read_timeout, write_timeout
-
keep_alive_time: optional, int, in seconds, default -1. Specifies the keep-alive detection interval for the connection.
-
read_timeout: optional, float or int, in seconds, default -1. Specifies the timeout for reading server responses.
-
write_timeout: optional, float or int, in seconds, default -1. Specifies the network timeout for underlying data writes.
Parameter conversion and precedence rules:
-
read_timeout and timeout: If timeout is not specified (or is None), a non-negative read_timeout is converted to the receive timeout in seconds. If a positive timeout is also specified, timeout takes precedence. If
timeout=timedelta(0)is specified (unlimited wait time), read_timeout in the same call is ignored. -
write_timeout and net_timeout: If a positive net_timeout is also specified, the shorter value is used as the write operation timeout.
-
keep_alive_time and net_timeout: keep_alive_time is converted to a network timeout based on the operating system:
keep_alive_time × 3seconds on Linux and macOS, andkeep_alive_time × 10seconds on Windows. If a positive net_timeout is also specified, the smaller of the converted value and net_timeout is used.
conn = ddb.DBConnection()
conn.connect(
"localhost",
8848,
read_timeout=30,
write_timeout=10,
)
Cluster address parameter use_public_name
-
use_public_name: optional, bool, default False. Specifies whether a high availability connection preferentially uses a node's publicName as the connection address.
use_public_name takes effect only when high availability is enabled
(enable_high_availability=True). If high availability is not
enabled, the connection address is still resolved according to the original logic
and is not affected by this parameter.
Before enabling this parameter, correctly configure publicName for the
relevant nodes on the server, and ensure that the client can resolve and access that
address while still being able to access the initial entry
host:port. The current implementation supports only one
non-empty external address. If publicName is configured as multiple addresses
separated by semicolons, no external address mapping is established, and the
connection still uses the node's internal address.
conn = ddb.DBConnection()
conn.connect(
"cluster.example.com",
8848,
enable_high_availability=True,
use_public_name=True,
)
ConnectionConfig
Connection parameters can be centrally stored in a ConnectionConfig
object or a dictionary. When a ConnectionConfig object is used,
directly passed parameters override the corresponding fields in the object. When a
dictionary is used, passing a parameter directly with the same name as a key that
already exists in the dictionary throws TypeError. If the directly
passed host, port, userid, or password is None, it does
not override the corresponding value in the configuration.
import dolphindb as ddb
config = ddb.ConnectionConfig(
host="localhost",
port=8848,
userid="admin",
password="your_password",
reconnect=True,
)
conn = ddb.DBConnection()
conn.connect(config=config)
Return values and error handling
connect() establishes a session. It returns True when the connection
succeeds, and usually returns False when the connection is not established. The
caller should decide whether to continue business operations based on the return
value, and pay attention to exceptions only when configuration or runtime issues
need to be diagnosed.
| Scenario | Result |
|---|---|
| Connection parameters are missing, unknown fields are specified, or field values do not comply with validation rules | A parameter validation exception is thrown, such as
pydantic.ValidationError or
TypeError |
| TCP connection establishment, handshake, authentication, or the retry process fails to establish an available connection | False is returned |
| The connection has been established, but the post-connection initialization script or finalization processing fails | A runtime exception is thrown, usually
RuntimeError |
| An unhandled error occurs while querying cluster information or switching nodes in high availability mode | A runtime exception is thrown, usually
RuntimeError |
Authentication failure during connection establishment is handled as a
connect() connection result. If login() is
called explicitly after the connection is established, authentication failure throws
RuntimeError.
