JdbcReader.scala 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package com.yiidata.amc.jdbc
  2. import java.util
  3. import java.util.Properties
  4. import org.apache.commons.dbcp.BasicDataSource
  5. import org.apache.commons.dbutils.QueryRunner
  6. import org.apache.commons.dbutils.handlers.MapListHandler
  7. /**
  8. * <p>
  9. * 从数据库中读取数据
  10. * </p>
  11. *
  12. * Created by ZhenQin on 2018/2/10 0010-10:35
  13. * Vendor: yiidata.com
  14. * @author ZhenQin
  15. */
  16. trait JdbcReader[T] {
  17. def read(sql:String, ps:Properties):T
  18. }
  19. /**
  20. * JDBC 读取表数据
  21. *
  22. * @author ZhenQin
  23. *
  24. */
  25. class JdbcRowReader extends JdbcReader[util.List[util.Map[String, AnyRef]]] {
  26. override def read(sql:String, ps: Properties): util.List[util.Map[String, AnyRef]] = {
  27. val dataSource = new BasicDataSource()
  28. dataSource.setMaxActive(1)
  29. dataSource.setMinIdle(1)
  30. dataSource.setInitialSize(1)
  31. dataSource.setDriverClassName(ps.getProperty("driver"))
  32. dataSource.setUrl(ps.getProperty("url"))
  33. dataSource.setUsername(ps.getProperty("user"))
  34. dataSource.setPassword(ps.getProperty("password"))
  35. val qr = new QueryRunner(dataSource)
  36. try {
  37. val list: util.List[util.Map[String, AnyRef]] = qr.query(sql, new MapListHandler())
  38. list
  39. } finally {
  40. dataSource.close()
  41. }
  42. }
  43. }