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();
    }
}
相关推荐
Apache Flink1 小时前
云栖实录|驰骋在数据洪流上:Flink+Hologres驱动零跑科技实时计算的应用与实践
大数据·科技·flink
准时准点睡觉1 小时前
window安装MYSQL5.5出错:a windows service with the name MYSQL alreadyexists....
数据库·windows·mysql
盈创力和20071 小时前
以太网多参量传感器:超越温湿度的“智能嗅探”,守护每一方空气的安全
大数据·人工智能
wudl55661 小时前
Flink Keyed State 详解之七
大数据·flink
wudl55661 小时前
Flink Keyed State 详解之六
大数据·flink
caiyueloveclamp2 小时前
便宜好用AIPPT推荐TOP8【2025最新】
大数据·人工智能·powerpoint·ai生成ppt·aippt·免费会员
想ai抽2 小时前
从文件结构、索引、数据更新、版本控制等全面对比Apache hudi和Apache paimon
大数据·架构·flink
葡萄城技术团队3 小时前
实战视角:为何专用小型语言模型(SLM)正成为企业 AI 选型新宠—与 LLM 的全面对比指南
大数据·人工智能·语言模型
GIS数据转换器3 小时前
科技赋能农业现代化的破局之道
大数据·科技·安全·机器学习·智慧城市·制造
PONY LEE3 小时前
Flink keyby使用随机数踩坑记
大数据·python·flink