PageRenderTime 25ms CodeModel.GetById 16ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

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