자바 통용 jdbc 데이터베이스 작업 클래스

30867 단어
package com.hy.fddsvr.utils;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.*;


public class DBManager {

    /**
     * @param args
     */
    static String driver;
    static String url;
    static String username;
    static String password;
    private Connection connection;
    private PreparedStatement pstmt;
    private ResultSet resultSet;

    public DBManager() {
        //     db.properties          
        InputStream in = DBManager.class.getClassLoader().getResourceAsStream("db.properties");
        Properties pro = new Properties();
        try {
            pro.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //     
        driver = pro.getProperty("driver");
        //     
        url = pro.getProperty("url");
        //      
        username = pro.getProperty("username");
        //     
        password = pro.getProperty("password");

        try {
            //     
            getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *         
     *
     * @return
     * @throws ClassNotFoundException
     */
    public Connection getConnection() {
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (Exception e) {
            System.out.println("fail to connect database");
        }
        return connection;
    }

    /**
     *     ID
     *
     * @param tableName
     * @return
     * @throws SQLException
     */
    public int getMaxId(String tableName) {
        Statement state = null;
        ResultSet rs = null;
        int maxId = 0;
        try {
            state = connection.createStatement();
            String sql = "select max(autoid) maxId from " + tableName;
            rs = state.executeQuery(sql);
            //  resultset        
            if (rs.next()) {
                maxId = rs.getInt("maxId");
            }
        } catch (Exception ex) {
            // TODO Auto-generated catch block
            ex.printStackTrace();
        }

        return ++maxId;
    }

    /**
     *     sql        
     *
     * @param sql
     * @return   true      ,  false       
     * @throws SQLException
     */
    public boolean CheckDataIsEmpty(String sql) {
        Statement state = null;
        ResultSet rs = null;
        boolean isempty=true;


        try {
            state = connection.createStatement();
            rs = state.executeQuery(sql);
            if (rs==null){
                isempty=true;
            }else{
                if(rs.next()){
                    isempty=false;
                }else{
                    isempty=true;
                }
            }
        } catch (Exception ex) {
            // TODO Auto-generated catch block
            ex.printStackTrace();
        }


        return isempty;
    }



    /**
     *     sql        
     *
     * @param sql
     * @return        
     * @throws SQLException
     */
    public String GetTopValue(String sql) {
        Statement state = null;
        ResultSet rs = null;
        String topvalue="";


        try {
            state = connection.createStatement();
            rs = state.executeQuery(sql);
            if (rs!=null){
                if(rs.next()){
                    topvalue = rs.getString(1);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }


        return topvalue;
    }

    /**
     *     sql        
     *
     * @param sql
     * @return        
     * @throws SQLException
     */
    public ResultSet GetTopDataSet(String sql) {
        Statement state = null;
        ResultSet rs = null;
        try {
            state = connection.createStatement();
            rs = state.executeQuery(sql);
            if (rs!=null){
                rs.next();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return rs;
    }


    /**
     *     sql       
     *
     * @param sql
     * @return       true,    false
     * @throws SQLException
     */
    public boolean ExecSql(String sql) {
        Statement state = null;
        int iflag=-1;
        boolean res=false;

        try {
            pstmt = connection.prepareStatement(sql);
            iflag = pstmt.executeUpdate();
            res = (iflag > 0 ? true : false);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return res;
    }


    /**
     *   、  、 
     *
     * @param sql
     * @param params
     * @return
     * @throws SQLException
     */
    public boolean updateByPreparedStatement(String sql, List params)
            throws SQLException {
        boolean flag = false;
        int result = -1;
        pstmt = connection.prepareStatement(sql);
        int index = 1;
        if (params != null && !params.isEmpty()) {
            for (int i = 0; i < params.size(); i++) {
                pstmt.setObject(index++, params.get(i));
            }
        }
        result = pstmt.executeUpdate();
        flag = result > 0 ? true : false;
        return flag;
    }

    /**
     *       
     *
     * @param sql
     * @param params
     * @return
     * @throws SQLException
     */
    public Map findSimpleResult(String sql, List params)
            throws SQLException {
        Map map = new HashMap();
        int index = 1;
        pstmt = connection.prepareStatement(sql);
        if (params != null && !params.isEmpty()) {
            for (int i = 0; i < params.size(); i++) {
                pstmt.setObject(index++, params.get(i));
            }
        }
        resultSet = pstmt.executeQuery();//       
        ResultSetMetaData metaData = resultSet.getMetaData();
        int col_len = metaData.getColumnCount();
        while (resultSet.next()) {
            for (int i = 0; i < col_len; i++) {
                String cols_name = metaData.getColumnName(i + 1);
                Object cols_value = resultSet.getObject(cols_name);
                if (cols_value == null) {
                    cols_value = "";
                }
                map.put(cols_name, cols_value);
            }
        }
        return map;
    }

    /**
     *       
     *
     * @param sql
     * @param params
     * @return
     * @throws SQLException
     */
    public List> findModeResult(String sql,
                                                    List params) throws SQLException {
        List> list = new ArrayList>();
        int index = 1;
        pstmt = connection.prepareStatement(sql);
        if (params != null && !params.isEmpty()) {
            for (int i = 0; i < params.size(); i++) {
                pstmt.setObject(index++, params.get(i));
            }
        }
        resultSet = pstmt.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int cols_len = metaData.getColumnCount();
        while (resultSet.next()) {
            Map map = new HashMap();
            for (int i = 0; i < cols_len; i++) {
                String cols_name = metaData.getColumnName(i + 1);
                Object cols_value = resultSet.getObject(cols_name);
                if (cols_value == null) {
                    cols_value = "";
                }
                map.put(cols_name, cols_value);
            }
            list.add(map);
        }

        return list;
    }

    /**
     *             
     *
     * @param sql
     * @param params
     * @param cls
     * @return
     * @throws Exception
     */
    public  T findSimpleRefResult(String sql, List params,
                                     Class cls) throws Exception {
        T resultObject = null;
        int index = 1;
        pstmt = connection.prepareStatement(sql);
        if (params != null && !params.isEmpty()) {
            for (int i = 0; i < params.size(); i++) {
                pstmt.setObject(index++, params.get(i));
            }
        }
        resultSet = pstmt.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int cols_len = metaData.getColumnCount();
        while (resultSet.next()) {
            //             
            resultObject = cls.newInstance();
            for (int i = 0; i < cols_len; i++) {
                String cols_name = metaData.getColumnName(i + 1);
                Object cols_value = resultSet.getObject(cols_name);
                int type = metaData.getColumnType(i + 1);
                if (cols_value == null) {
                    if (type == Types.INTEGER) {
                        cols_value = 0;
                    } else {
                        cols_value = "";
                    }
                }
                Field field = cls.getDeclaredField(cols_name.toLowerCase());
                field.setAccessible(true); //   javabean     
                if (type == Types.TIMESTAMP) {
                    field.set(resultObject, String.valueOf(cols_value));
                } else {
                    field.set(resultObject, cols_value);
                }
            }
        }
        return resultObject;

    }

    /**
     *             
     *
     * @param sql
     * @param params
     * @param cls
     * @return
     * @throws Exception
     */
    public  List findMoreRefResult(String sql, List params,
                                         Class cls) throws Exception {
        List list = new ArrayList();
        int index = 1;
        pstmt = connection.prepareStatement(sql);
        if (params != null && !params.isEmpty()) {
            for (int i = 0; i < params.size(); i++) {
                pstmt.setObject(index++, params.get(i));
            }
        }
        resultSet = pstmt.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int cols_len = metaData.getColumnCount();
        while (resultSet.next()) {
            //             
            T resultObject = cls.newInstance();
            for (int i = 0; i < cols_len; i++) {
                String cols_name = metaData.getColumnName(i + 1);
                Object cols_value = resultSet.getObject(cols_name);
                if (cols_value == null) {
                    cols_value = "";
                }
                Field field = cls.getDeclaredField(cols_name);
                field.setAccessible(true); //   javabean     
                field.set(resultObject, cols_value);
            }
            list.add(resultObject);
        }
        return list;
    }

    /**
     *        
     */
    public void releaseConn() {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

 
resources 디 렉 터 리 아래 dbo. properties 파일 을 만 듭 니 다. 내용:
driver = com.microsoft.sqlserver.jdbc.SQLServerDriver
url = jdbc:sqlserver://localhost:1433;DatabaseName=MyDB;
username = sa
password = 123

 
호출 방식:
DBManager db=new DBManager();
db.ExecSql("update mytb set a1=0 where b1 is null");

좋은 웹페이지 즐겨찾기