WHCSRL 技术网

java获取数据库数据保存到本地txt文件中

首先是Services

  1. @Service
  2. public class logServiceimpl implements logService {
  3. @Autowired
  4. @Qualifier("primaryJdbcTemplate")
  5. protected JdbcTemplate jdbcTemplate;
  6. @Override
  7. public List<lockLog> getlog() {
  8. String sql="show OPEN TABLES where In_use > 0;";
  9. List<Map<String, Object>> list= jdbcTemplate.queryForList(sql);
  10. JSONArray jsonArray = new JSONArray();
  11. jsonArray.addAll(list);
  12. List<lockLog> lockLogList = jsonArray.toJavaList(lockLog.class);
  13. return lockLogList;
  14. }
  15. }

然后是Controller

  1. @Component
  2. public class runCron {
  3. @Resource
  4. private logService logservice;
  5. @Value("${dir}")
  6. private String dir;
  7. @Scheduled(cron="0 0/1 * * * ?") //每一分钟执行一次
  8. public void getlog() throws IOException {
  9. List<lockLog> mapList = logservice.getlog();
  10. File file = new File(dir);
  11. if (!file.exists()) {
  12. file.createNewFile();
  13. }
  14. //true 禁止覆盖之前的数据
  15. FileWriter fileWriter=new FileWriter(file,true);
  16. PrintWriter fout = new PrintWriter(fileWriter);
  17. SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  18. Date date = new Date(System.currentTimeMillis());
  19. fout.write(formatter.format(date));
  20. String huanhang = System.getProperty("line.separator");
  21. fout.write(huanhang);
  22. for (int i = 0; i < mapList.size(); i++) {
  23. lockLog sql = (lockLog) mapList.get(i);
  24. String content = sql.getDatabase() + " " + sql.getTable() + " " + sql.getIn_use() + " " + sql.getName_locked();
  25. fout.write(content);
  26. huanhang = System.getProperty("line.separator");
  27. fout.write(huanhang);
  28. }
  29. fout.flush();
  30. fout.close();
  31. }
  32. }

最后是配置文件application.properties

  1. dir=D:\aaa.txt
  2. spring.datasource.primary.jdbc-url=jdbc:mysql://192.168.xx:xx/xx
  3. spring.datasource.primary.username=xx
  4. spring.datasource.primary.password=xx
  5. spring.datasource.primary.driver-class-name= com.mysql.cj.jdbc.Driver

推荐阅读