/db-migrate/src/main/java/com/googlecode/hdbc/dbmigrate/io/DatabaseProvider.java

http://hdbc.googlecode.com/ · Java · 75 lines · 67 code · 8 blank · 0 comment · 7 complexity · f9f9412c054ec3a7674c7f13107cf0a0 MD5 · raw file

  1. package com.googlecode.hdbc.dbmigrate.io;
  2. import java.sql.Connection;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import java.util.Properties;
  7. import javax.sql.DataSource;
  8. import oracle.jdbc.pool.OracleDataSource;
  9. public class DatabaseProvider implements IDatabaseProvider {
  10. private Properties props;
  11. public DatabaseProvider(Properties properties) {
  12. props = properties;
  13. }
  14. @Override
  15. public int getCurrentVersion() throws SQLException {
  16. int version = 0;
  17. DataSource ds = this.makeDataSource(props);
  18. Connection cn = null;
  19. Statement stmt = null;
  20. try {
  21. cn = ds.getConnection();
  22. stmt = cn.createStatement();
  23. stmt.execute("SELECT version FROM version");
  24. ResultSet rs = stmt.getResultSet();
  25. if (rs.next()) {
  26. version = rs.getInt(1);
  27. }
  28. } finally {
  29. if (stmt != null) {
  30. try {
  31. stmt.close();
  32. } catch (SQLException e) {}
  33. }
  34. if (cn != null) {
  35. try {
  36. cn.close();
  37. } catch (SQLException e) {}
  38. }
  39. }
  40. this.closeDatasource(ds);
  41. return version;
  42. }
  43. protected final DataSource makeDataSource(final Properties props) {
  44. OracleDataSource ods;
  45. try {
  46. ods = new OracleDataSource();
  47. ods.setConnectionCachingEnabled(true);
  48. String url = props.getProperty("db.jdbc.connection.string");
  49. ods.setURL(url);
  50. String user = props.getProperty("db.user");
  51. ods.setUser(user);
  52. String pwd = props.getProperty("db.password");
  53. ods.setPassword(pwd);
  54. } catch (SQLException e) {
  55. throw new IllegalStateException(e);
  56. }
  57. return ods;
  58. }
  59. private void closeDatasource(final DataSource ds) {
  60. if (ds == null) {
  61. return;
  62. }
  63. try {
  64. ((OracleDataSource) ds).close();
  65. } catch (SQLException e) {}
  66. }
  67. }