Connect to TiDB
This guide shows how to connect to a TiDB database using the pytidb client.
Install the dependencies
pytidb is a Python client built on SQLAlchemy. It provides a series of high-level APIs to help you store and search vector embeddings without writing raw SQL.
To install the Python client, run the following command:
pip install pytidb
Connect with connection parameters
Choose the steps based on your TiDB deployment type:
You can create a TiDB Cloud Starter cluster, and then get the connection parameters from the web console as follows:
- Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.
- Click Connect in the upper-right corner. A connection dialog is displayed, with connection parameters listed.
- Copy the connection parameters to your code or environment variables.
Example code:
from pytidb import TiDBClient
db = TiDBClient.connect(
host="{gateway-region}.prod.aws.tidbcloud.com",
port=4000,
username="{prefix}.root",
password="{password}",
database="test",
)
Follow Quick Start with TiDB Self-Managed to deploy a TiDB cluster for testing.
Example code:
from pytidb import TiDBClient
db = TiDBClient.connect(
host="{tidb_server_host}",
port=4000,
username="root",
password="{password}",
database="test",
)
Once connected, you can use the db object to operate tables, query data, and more.
Connect with connection string
If you prefer to use a connection string (database URL), you can follow the format based on your deployment type:
You can create a TiDB Cloud Starter cluster, and then get the connection parameters from the web console as follows:
- Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.
- Click Connect in the upper-right corner. A connection dialog is displayed, with the connection parameters listed.
- Copy the connection parameters and construct a connection string in the following format:
from pytidb import TiDBClient
db = TiDBClient.connect(
database_url="mysql+pymysql://{USERNAME}:{PASSWORD}@{HOST}:{PORT}/{DATABASE}?ssl_verify_cert=true&ssl_verify_identity=true",
)
You can follow the format below to construct the connection string:
from pytidb import TiDBClient
db = TiDBClient.connect(
database_url="mysql+pymysql://{USERNAME}:{PASSWORD}@{HOST}:{PORT}/{DATABASE}",
)
Connect with SQLAlchemy DB engine
If your application already has a SQLAlchemy database engine, you can reuse it via the db_engine parameter:
from pytidb import TiDBClient
db = TiDBClient(db_engine=db_engine)
Next steps
After connecting to your TiDB database, you can explore the following guides to learn how to work with your data:
- Working with Tables: Learn how to define and manage tables in TiDB.
- Vector Search: Perform semantic search using vector embeddings.
- Full-Text Search: Retrieve documents using keyword-based search.
- Hybrid Search: Combine vector and full-text search for more relevant results.