zoukankan      html  css  js  c++  java
  • JDBC的crud通用方法

    package com.platform_db.dao.impl;

    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;

    import com.platform_db.dao.IObjectDao;
    import com.platform_db.db.DBUtil;

    public class ObjectDaoImpl implements IObjectDao{
    public List<?> find(String sql,Object[] pars) throws Exception {
    PreparedStatement ps = null;
    ResultSet rs = null;

    Connection conn = DBUtil.openConnection();
    ps = conn.prepareStatement(sql);
    for (int i = 0;i < pars.length ; i++) {
    ps.setObject(i+1, pars[i]);
    }
    rs = ps.executeQuery();

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

    ResultSetMetaData md = rs.getMetaData();
    int columnCount = md.getColumnCount();
    while( rs.next() ){
    Map<String , Object> map = new HashMap<String , Object>();
    for (int i = 1; i <= columnCount; i++) {
    map.put(md.getColumnName(i), rs.getObject(i));
    }
    data.add(map);
    }

    rs.close();
    ps.close();
    conn.close();

    return data;
    }

    public boolean exec(String sql, Object[] pars) throws Exception {
    Connection conn = DBUtil.openConnection();
    conn.setAutoCommit(false);

    PreparedStatement ps = conn.prepareStatement(sql);
    for (int i = 0;i < pars.length ; i++) {
    ps.setObject(i+1, pars[i]);
    }
    boolean flag = ps.execute();

    conn.commit();
    conn.setAutoCommit(true);
    ps.close();
    conn.close();
    return flag;
    }

    public int[] execBatch(String sql, List<Object[]> list) throws Exception {
    Connection conn = DBUtil.openConnection();
    conn.setAutoCommit(false);

    PreparedStatement ps = conn.prepareStatement(sql);
    for(Object[] pars : list){
    for (int i = 0;i < pars.length ; i++) {
    ps.setObject(i+1, pars[i]);
    }
    ps.addBatch();
    }

    int[] counts = ps.executeBatch();

    conn.commit();
    conn.setAutoCommit(true);
    ps.close();
    conn.close();

    return counts;
    }
    }

  • 相关阅读:
    Linux中ctrl+z 、ctrl+c、 ctrl+d区别
    linux文件与用户权限的设置
    查找jdk的安装目录
    linux上修改防火墙操作
    linux上打包与压缩操作
    安装hive操作参考视频
    linux上设置环境变量每次需要source /etc/profile问题处理
    【c语言趣味编程100例】出售金鱼
    【c语言趣味编程100例】三色球问题
    【c语言】递归实现strlen()函数
  • 原文地址:https://www.cnblogs.com/lbblog/p/4705737.html
Copyright © 2011-2022 走看看