Programming/Java

[JDBC] 간단한 DB 매니저

Lawmin 2014. 8. 5. 14:09

VO 쓰기 귀찮을 때...

String으로만 처리하는 단점이 있으니

필요한 경우, jdbc type - java type 매핑테이블에 따라 바꿔야 할 듯


package com.manager;


import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.ResultSetMetaData;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;


import javax.naming.InitialContext;

import javax.naming.NamingException;

import javax.sql.DataSource;


public class DbManager {

private static final DbManager instance = new DbManager();

private DataSource ds;


private DbManager() {

InitialContext ic;

try {

ic = new InitialContext();

// 운영

//ds = (DataSource)ic.lookup("java:comp/env/jdbc/prod");

// 개발

ds = (DataSource)ic.lookup("java:comp/env/jdbc/dev");

} catch (NamingException e) {

e.printStackTrace();

}

}


public static DbManager getInstance() {

return instance;

}


public Connection getConnection() throws SQLException {

return ds.getConnection();

}

public List<Map<String, String>> getRowList(PreparedStatement pstmt) {

List<Map<String, String>> list = new ArrayList<Map<String, String>>();

ResultSet rs = null;

try {

rs = pstmt.executeQuery();

ResultSetMetaData rsmd = rs.getMetaData();

int colCnt = rsmd.getColumnCount();

String[] colNames = new String[colCnt];

for(int i = 0; i < colCnt; ++i) {

colNames[i] = rsmd.getColumnName(i + 1).toUpperCase();

}

while(rs.next()) {

Map<String, String> map = new HashMap<String, String>();

for(int i = 0; i < colCnt; ++i) {

map.put(colNames[i], rs.getString(i + 1));

}

list.add(map);

}

}

catch(Exception e) {

e.printStackTrace();

}

finally{

try { if(rs != null) { rs.close(); } } catch(Exception e) {}

}

return list;

}

public void safeClose(ResultSet rs, Statement stmt, Connection con) {

try { if(rs != null) { rs.close(); } } catch(Exception e) {}

try { if(stmt != null) { stmt.close(); } } catch(Exception e) {}

try { if(con != null) { con.close(); } } catch(Exception e) {}

}

}