Last active
June 27, 2019 20:43
-
-
Save madan712/d890822770530ae908b1d91395b1c016 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.javaxp; | |
import java.io.BufferedWriter; | |
import java.io.File; | |
import java.io.FileWriter; | |
import java.io.IOException; | |
import java.util.List; | |
import java.util.Map; | |
import java.util.stream.Collectors; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.boot.CommandLineRunner; | |
import org.springframework.boot.SpringApplication; | |
import org.springframework.boot.autoconfigure.SpringBootApplication; | |
import org.springframework.jdbc.core.JdbcTemplate; | |
@SpringBootApplication | |
public class Application implements CommandLineRunner { | |
@Autowired | |
private JdbcTemplate jdbcTemplate; | |
public static void main(String[] args) { | |
SpringApplication.run(Application.class, args); | |
} | |
public void run(String... args) throws Exception { | |
// Export database table | |
export("TABLE_1"); | |
export("TABLE_2"); | |
} | |
public void export(String tableName) { | |
writeCSVFile(tableName + ".csv", getData(tableName)); | |
} | |
public void writeCSVFile(String fileName, List<Map<String, Object>> data) { | |
try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File(fileName)))) { | |
data.forEach(rowData -> { | |
try { | |
bw.write(String.join(",", rowData.values().stream().map(Object::toString).collect(Collectors.toList()))); | |
bw.newLine(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
}); | |
bw.flush(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
public List<Map<String, Object>> getData(String tableName) { | |
String sqlQuery = "SELECT * FROM " + tableName; | |
return jdbcTemplate.queryForList(sqlQuery); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment