class mysql_source extends RichSourceFunction[ ( Long , String , Long ) ] {
private var connection: Connection = null
private var ps: PreparedStatement = null
override def open( parameters: Configuration) : Unit = {
val driver = "com.mysql.jdbc.Driver"
val url = "jdbc:mysql://localhost:3306/story"
val username = "root"
val password = "root"
Class. forName( driver)
connection = DriverManager. getConnection( url, username, password)
val sql = "select id, name,age from user"
ps = connection. prepareStatement( sql)
}
override def close( ) : Unit = {
if ( connection != null ) {
connection. close( )
}
if ( ps != null ) {
ps. close( )
}
}
override def run( sourceContext: SourceContext[ ( Long , String , Long ) ] ) : Unit = {
val queryRequest = ps. executeQuery( )
while ( queryRequest. next( ) ) {
val id = queryRequest. getLong( "id" )
val name = queryRequest. getString( "name" )
val age = queryRequest. getLong( "age" )
sourceContext. collect( ( id, name, age) )
}
}
override def cancel( ) : Unit = { }
}
val env: StreamExecutionEnvironment = StreamExecutionEnvironment. getExecutionEnvironment
val mysqlTable: DataStream[ ( Long , String , Long ) ] = env. addSource( new mysql_source( ) )