方式一 通过JDBCOutputFormat
在flink中没有现成的用来写入MySQL的sink,但是flink提供了一个类,JDBCOutputFormat,通过这个类,如果你提供了jdbc的driver,则可以当做sink使用。
JDBCOutputFormat其实是flink的batch api,但也可以用来作为stream的api使用,社区也推荐通过这种方式来进行。
JDBCOutputFormat用起来很简单,只需要一个prepared statement,driver和database connection,就可以开始使用了。
1 JDBCOutputFormat jdbcOutput =JDBCOutputFormat.buildJDBCOutputFormat()2 .setDrivername("com.mysql.jdbc.Driver")3 .setDBUrl("jdbc:mysql://localhost:1234/test?user=xxx&password=xxx")4 .setQuery(query)5 .finish();
如下的sql语句可以作为prepared statement:
String query = "INSERT INTO public.cases (caseid, tracehash) VALUES (?, ?)";
对应的表的结构:
1 CREATE TABLE cases2 (3 caseid VARCHAR(255),4 tracehash VARCHAR(255)5 );
但有一点要明确,JDBCOutputFormat只能处理Row,而Row是对prepared statement的参数的一个包装