flink jdbc连接器

  flink提供很多访问其他数据源的连接器,访问其他第三方数据源变得简单高效。下面就是flink提供的一些连接器,使用时只需引入需要的包。

  flink jdbc连接器_第1张图片

在使用flink处理数据后,我们经常会将结果写入数据库,供其它业务使用。

 

  private static String  driverClass = "com.mysql.jdbc.Driver";
    private static String dbUrl = "jdbc:mysql://192.168.1.100:3306/test";
    private static String userNmae = "root";
    private static String passWord = "123456";

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource input = env.fromCollection(Arrays.asList(new Person("123", 25), new Person("456", 24)));
        DataStream  ds = input.map(new RichMapFunction() {
            @Override
            public Row map(Person person) throws Exception {
                return Row.of(person.getAge(),person.getName());
            }
        });
        TypeInformation[] fieldTypes = new TypeInformation[] {
                BasicTypeInfo.INT_TYPE_INFO,
                BasicTypeInfo.STRING_TYPE_INFO


        };

        RowTypeInfo rowTypeInfo = new RowTypeInfo(fieldTypes);
        //写入mysql
        JDBCAppendTableSink sink = JDBCAppendTableSink.builder()
                .setDrivername(driverClass)
                .setDBUrl(dbUrl)
                .setUsername(userNmae)
                .setPassword(passWord)
                .setParameterTypes(fieldTypes)
//                .setQuery("insert into student values(?,?)")
                .setQuery("update student set age = ? where name = ?")
                .build();

        sink.emitDataStream(ds);
          
        //查询mysql
        JDBCInputFormat jdbcInputFormat = JDBCInputFormat.buildJDBCInputFormat()
              		.setDrivername(driverClass)
             			.setDBUrl(dbUrl)
                        .setUsername(userNmae)
                        .setPassword(passWord)
            			.setQuery("select * from student")
             			.setRowTypeInfo(rowTypeInfo)
             		    .finish();
        DataStreamSource input1 = env.createInput(jdbcInputFormat);
        input1.print();
        env.execute();
    }

注意传入参数Row 字段顺序 , fieldTypes 类型,一定要与sql语句的参数类型顺序保持一致。

你可能感兴趣的:(flink)