JDBC简单封装

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 = 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 = result.getObject(cols_name);  

               if (cols_value == null) {  

                   cols_value = "";  

               }  

               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简单封装的主要内容,如果未能解决你的问题,请参考以下文章

简单封装JDBC

java对jdbc操作结果简单的映射封装

利用jdbc简单封装一个小框架(类似DBUtils)

jdbc中对mysql数据库操作的简单封装--(仅做备忘记录)

什么是Java的封装类

Java通过JDBC 进行Dao层的封装