首页 > 代码库 > JDBC简单封装

JDBC简单封装

/**

 * JDBC简单封装

 * 需要借助FastJsonUtil可以参考上一篇

 * @author huangxincheng

 *

 */

public class BaseDao {

private static String URL;

private static String USERNAME;

private static String PASSWORD;

private static String DRIVER;

private  Connection connection;

private  PreparedStatement pstmt;

private  ResultSet result;

static {

try {

InputStream inputStream = BaseDao.class.getClassLoader().getResourceAsStream("jdbc.properties");

Properties prop = new Properties();

prop.load(inputStream);

USERNAME = prop.getProperty("jdbc.username");  

PASSWORD = prop.getProperty("jdbc.password");  

DRIVER= prop.getProperty("jdbc.driver");  

URL = prop.getProperty("jdbc.url");

} catch (IOException e) {

throw new RuntimeException("load db properties faild");

}  

}

//获取连接

private  Connection getConnection() {

try {

Class.forName(DRIVER);// 注册驱动  

connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); // 获取连接

return connection;

} catch (Exception e) {

throw new RuntimeException("register db driver faild");

}

private PreparedStatement getStatement(String sql, Object ... objs) {

try {

pstmt = connection.prepareStatement(sql);

if (objs != null) {

for (int i = 0; i < objs.length; i++) {

pstmt.setObject(i+1, objs[i]);

}

}

return pstmt;

} catch (SQLException e) {

throw new RuntimeException("pstmt faild");

}

}

private <T> List<T> findResult(Class<T> clazz, String sql, Object ... objs) {

try {

getConnection();

getStatement(sql, objs);

result = pstmt.executeQuery();

ResultSetMetaData metaData = http://www.mamicode.com/result.getMetaData();

   int cols_len = metaData.getColumnCount();

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

   Map<String, Object> map = null;

   while (result.next()) {  

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

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

               String cols_name = metaData.getColumnLabel(i + 1);  

               Object cols_value = http://www.mamicode.com/result.getObject(cols_name);

               if (cols_value =http://www.mamicode.com/= null) {

                   cols_valuehttp://www.mamicode.com/= "";  

               }  

               map.put(cols_name, cols_value);  

      }  

      list.add(map);  

   }

   if (list.size() > 0) {

    List<T> result = FactJsonUtil.parseList(FactJsonUtil.toJson(list), clazz);

   return result;

   }

   return null;

} catch (SQLException e) {

throw new RuntimeException("result faild");

}  finally {

releaseConn();

}

}

/** 

     * 释放资源 

     */  

private  void releaseConn() {  

        if (result != null) {  

            try {  

                result.close();  

            } catch (SQLException e) {  

                e.printStackTrace();  

            }  

        }  

        if (pstmt  != null) {  

            try {  

            pstmt.close();  

            } catch (SQLException e) {  

                e.printStackTrace();  

            }  

        }  

        if (connection != null) {  

            try {  

                connection.close();  

            } catch (SQLException e) {  

                e.printStackTrace();  

            }  

        }  

    } 

@SuppressWarnings("main")

public static void main(String[] args) {

// List<TbTest> list = new BaseDao().findResult(TbTest.class, "select * from tb_test", null);

// for (TbTest tbTest : list) {

// System.out.println(tbTest.getId() + ":" + tbTest.getName() + ":" + tbTest.getSex());

// }

String sql = "SELECT"+

" t1.id as item_id,t1.title as item_title,"+

" t1.sell_point as item_sell_point,"+

" t1.price as item_price,"+

   " t1.num as item_num,t1.image as item_image,"+

" t2.name as item_cname,"+

" t3.item_desc"+

 " FROM"+

" tb_item t1"+

     " LEFT JOIN tb_item_cat t2 ON t1.cid = t2.id"+

   " LEFT JOIN tb_item_desc t3 ON t1.id = t3.item_id"+

" where t1.id = ?";

List<SolrItem> list = new BaseDao().findResult(SolrItem.class, sql, 844022);

if (list != null && list.size() > 0) {

for (SolrItem solrItem : list) {

System.err.println(solrItem);

}

}

}

}


本文出自 “12265610” 博客,谢绝转载!

JDBC简单封装