> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# JDBC 表引擎

> 允许 ClickHouse 通过 JDBC 连接外部数据库。

[ClickHouse Cloud 不支持此功能](https://clickhouse.com/docs/products/cloud/guides/cloud-compatibility.md#list-of-unsupported-features)

> [!NOTE]
>
> clickhouse-jdbc-bridge 包含 Experimental 代码，且已不再受支持。它可能存在可靠性问题和安全漏洞，请自行承担使用风险。
> ClickHouse 建议使用其内置的表函数，在临时查询场景 (如 Postgres、MySQL、MongoDB 等) 中可作为更好的替代方案。

允许 ClickHouse 通过 [JDBC](https://en.wikipedia.org/wiki/Java_Database_Connectivity) 连接外部数据库。

为实现 JDBC 连接，ClickHouse 使用独立程序 [clickhouse-jdbc-bridge](https://github.com/ClickHouse/clickhouse-jdbc-bridge)，该程序应以守护进程方式运行。

此引擎支持 [Nullable](https://clickhouse.com/docs/zh/reference/data-types/nullable.md) 数据类型。

## 创建表

```sql theme={null}
CREATE TABLE [IF NOT EXISTS] [db.]table_name
(
    columns list...
)
ENGINE = JDBC(datasource, external_database, external_table)
```

**引擎参数**

* `datasource` — 外部 DBMS 的 URI 或名称。

  URI 格式：`jdbc:<driver_name>://<host_name>:<port>/?user=<username>&password=<password>`。
  MySQL 示例：`jdbc:mysql://localhost:3306/?user=root&password=root`。

* `external_database` — 外部 DBMS 中的数据库名称，或者显式定义的表 schema (见示例) 。

* `external_table` — 外部数据库中的表名，或类似 `select * from table1 where column1=1` 的 SELECT 查询。

* 这些参数也可以通过[命名集合](https://clickhouse.com/docs/zh/concepts/features/configuration/server-config/named-collections.md)传递。

## 使用示例

通过直接连接 MySQL 服务器的控制台客户端来创建表：

```text theme={null}
mysql> CREATE TABLE `test`.`test` (
    ->   `int_id` INT NOT NULL AUTO_INCREMENT,
    ->   `int_nullable` INT NULL DEFAULT NULL,
    ->   `float` FLOAT NOT NULL,
    ->   `float_nullable` FLOAT NULL DEFAULT NULL,
    ->   PRIMARY KEY (`int_id`));
Query OK, 0 rows affected (0,09 sec)

mysql> insert into test (`int_id`, `float`) VALUES (1,2);
Query OK, 1 row affected (0,00 sec)

mysql> select * from test;
+------+----------+-----+----------+
| int_id | int_nullable | float | float_nullable |
+------+----------+-----+----------+
|      1 |         NULL |     2 |           NULL |
+------+----------+-----+----------+
1 row in set (0,00 sec)
```

在 ClickHouse server 中创建表并查询其中的数据：

```sql theme={null}
CREATE TABLE jdbc_table
(
    `int_id` Int32,
    `int_nullable` Nullable(Int32),
    `float` Float32,
    `float_nullable` Nullable(Float32)
)
ENGINE JDBC('jdbc:mysql://localhost:3306/?user=root&password=root', 'test', 'test')
```

```sql theme={null}
SELECT *
FROM jdbc_table
```

```text theme={null}
┌─int_id─┬─int_nullable─┬─float─┬─float_nullable─┐
│      1 │         ᴺᵁᴸᴸ │     2 │           ᴺᵁᴸᴸ │
└────────┴──────────────┴───────┴────────────────┘
```

```sql theme={null}
INSERT INTO jdbc_table(`int_id`, `float`)
SELECT toInt32(number), toFloat32(number * 1.0)
FROM system.numbers
```

## 另请参阅

* [JDBC 表函数](https://clickhouse.com/docs/zh/reference/functions/table-functions/jdbc.md).
