Jdbc 增刪改查工具方法

/**
* 查詢數據列表
* @param sql 查詢SQL語句
* @param queryColum 要查詢的字段
* @param type 查詢類型 當type = "count" 爲查詢總條數
* @throws SQLException
*/
public static List<Map<String,Object>>  query(String sql,String queryColum,String type,String timeColum) throws SQLException{
Connection conn = DbUtils.getConnection();
PreparedStatement st = conn.prepareStatement(sql);
List<Map<String,Object>> list  = new ArrayList<Map<String,Object>>();
ResultSet result = st.executeQuery(sql);
if("count".equals(type)){//查詢總條數
            while(result.next()){
            Map<String,Object> map = new HashMap<String, Object>();
String  total = result.getString("total");
map.put("total", total);
list.add(map);
}
}
if(null !=queryColum && !"".equals(queryColum)){
while(result.next()){

Map<String,Object> map = new HashMap<String, Object>();
String[] clounName = queryColum.split(",");

for (String s : clounName) {
if(s.trim().equals(timeColum)){
long ll = result.getLong(s);
map.put(s, Tools.transLong2Date(ll));
}else{
map.put(s, result.getString(s).replaceAll("<", "").replaceAll(">", ""));
}

}
list.add(map);
}
}
result.close();
st.close();
conn.close();
return list;
}


/**
* 更新
* @param string
* @param type 當type 爲del是不拆分
* @param updateColumnValue
* @throws SQLException 
*/
public static int  update(String sql, String updateColumn,String type) throws SQLException {
Connection conn = DBAccesser.getMachineConnection();
PreparedStatement ps = null;
int status = 0;
if(null != updateColumn && !"".equals(updateColumn)){
ps =  conn.prepareStatement(sql);
if(!"del".equals(type)){
String[] array = updateColumn.split(",");
    for (int i = 0; i < array.length; i++) {
ps.setString(i+1, array[i]);
}
}else{
ps.setString(1, updateColumn);
}

    status = ps.executeUpdate();
}
ps.close();
conn.close();
return status;
}


public static int update2(String sql) throws SQLException{
Connection conn = DBAccesser.getMachineConnection();
Statement ps = null;
int i =0;
    try {
      ps = conn.createStatement();
          i = ps.executeUpdate(sql);
        ps.close();
        conn.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return i;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章