Flink Table API 读写MySQL

java 复制代码
import org.apache.flink.connector.jdbc.table.JdbcConnectorOptions;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.Schema;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.TableDescriptor;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.table.api.TableResult;

import static org.apache.flink.table.api.Expressions.$;

public class TableApiMysql {
    public static void main(String[] args) {
        EnvironmentSettings settings = EnvironmentSettings.newInstance().inBatchMode().build();
        TableEnvironment tableEnv = TableEnvironment.create(settings);

        Schema schema = Schema.newBuilder()
                .column("user_id", DataTypes.BIGINT())
                .column("user_name", DataTypes.STRING())
                .build();

        TableDescriptor tableDescriptor = TableDescriptor.forConnector("jdbc")
                .option(JdbcConnectorOptions.URL, "jdbc:mysql://localhost:3306/tmp")
                .option(JdbcConnectorOptions.USERNAME, "root")
                .option(JdbcConnectorOptions.PASSWORD, "123456")
                .option(JdbcConnectorOptions.TABLE_NAME, "test")
                .schema(schema)
                .build();

        tableEnv.createTable("source", tableDescriptor);

        // 通过API执行select
        System.out.println("select format 1: ");
        tableEnv.from("source").select($("user_id"), $("user_name")).execute().print();

        // 写入mysql user_id是自增主键
        tableEnv.executeSql("insert into source(user_name) select 'hello'");

        // 直接SQL执行select *
        System.out.println("select format 2: ");
        Table table = tableEnv.sqlQuery("select * from source");
        TableResult execute = table.execute();
        execute.print();
    }
}
相关推荐
黎阳之光2 小时前
黎阳之光:以视频孪生重构智慧防火,打造“天空地人智”一体化森林防火新范式
大数据·运维·人工智能·物联网·安全
Daydream.V3 小时前
Python Flask超全入门实战教程|从零基础到项目部署
大数据·python·flask
我是一颗柠檬6 小时前
【MySQL全面教学】MySQL基础SQL语句Day3(2026年)
数据库·后端·sql·mysql·oracle
MandalaO_O6 小时前
MyBatis 与 MySQL 执行流程
数据库·mysql·mybatis
SmartBrain6 小时前
AI全栈开发(SDD):慢病管理系统工程级设计
java·大数据·开发语言·人工智能·架构·aigc
zandy10117 小时前
2026 BI平台与数据中台融合架构实践:从数据烟囱到统一智能数据层
大数据·架构·spark
键盘上的猫头鹰8 小时前
【从零学MySQL(三)】数据增删改(DML)及 SELECT 查询详解
数据库·mysql·数据分析
金智维科技官方9 小时前
圆桌对话:从流程自动化到智能流程,AI落地的下一站在哪里?
大数据·人工智能·ai·自动化·智能体
Cry丶9 小时前
WebFlux + R2DBC 场景下的分库分表预研:从架构选型到落地风险
mysql·postgresql·数据库架构·shardingsphere·分库分表·webflux·r2dbc