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();
    }
}
相关推荐
思成不止于此3 小时前
【MySQL 零基础入门】DQL 核心语法(二):表条件查询与分组查询篇
android·数据库·笔记·学习·mysql
Jackeyzhe4 小时前
Flink学习笔记:状态类型和应用
flink
九河云4 小时前
华为云 ECS 弹性伸缩技术:应对业务峰值的算力动态调度策略
大数据·服务器·人工智能·物联网·华为云
帝吃藕和5 小时前
MySQL 知识点复习- 4. update/delete/like
mysql
AI营销资讯站5 小时前
AI营销内容生产:哪些平台支持全球多语言内容同步生产?
大数据·人工智能
杨云龙UP5 小时前
MySQL 自动备份与覆盖恢复实战:一套脚本搞定全库/按库备份恢复
linux·运维·数据库·sql·mysql
桃花键神6 小时前
openFuyao在AI推理与大数据场景中的加速方案:技术特性与实践探索
大数据·人工智能
天远数科8 小时前
前端全栈进阶:使用 Node.js Crypto 模块处理 AES 加密与天远API数据聚合
大数据·api
天远API8 小时前
后端进阶:使用 Go 处理天远API的 KV 数组结构与并发风控
大数据·api
千匠网络8 小时前
S2B供应链平台:优化资源配置,推动产业升级
大数据·人工智能·产品运营·供应链·s2b