Util(ORACLE)类
Constant.java
package com.bms.common.util;
public abstract class Constant {
final static String DRIVER_CLASS="oracle.jdbc.driver.OracleDriver";
final static String URL="jdbc:oracle:thin:@127.0.0.1:1521:ORCL";
final static String USERNAME="scott";
final static String PASSWORD="tiger";
}
ArrayUtil.java
package com.bms.common.util;
public class ArrayUtil {
public static boolean isBlank(Object...objects){
return objects!=null && objects.length>0;
}
}
SQLUtil.java
package com.bms.common.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SQLUtil extends Constant{
private static Connection getConnection(){
Connection conn=null;
try {
Class.forName(DRIVER_CLASS);
conn=DriverManager.getConnection(URL,USERNAME,PASSWORD);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public static Integer executeUpdate(String sql,Object...parameters){
Integer row=0;
Connection conn=getConnection();
PreparedStatement pst=null;
try {
pst=conn.prepareStatement(sql);
if(ArrayUtil.isBlank(parameters)){
for (int i = 0; i < parameters.length; i++) {
pst.setObject(i+1, parameters[i]);
}
}
row=pst.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeObject(pst,conn);
}
return row;
}
private static void closeObject(Object...parameters){
try {
if(ArrayUtil.isBlank(parameters)){
for (Object obj : parameters) {
if(obj instanceof ResultSet){
((ResultSet) obj).close();
}
if(obj instanceof PreparedStatement){
((PreparedStatement) obj).close();
}
if(obj instanceof Connection){
Connection conn=(Connection) obj;
if(!conn.isClosed()){
conn.close();
conn=null;
}
}
}
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static List<Map<String,Object>> executeQuery(String sql,Object...parameters){
Connection conn=getConnection();
PreparedStatement pst=null;
ResultSet rs=null;
List<Map<String,Object>> table=new ArrayList<Map<String,Object>>();
try {
pst=conn.prepareStatement(sql);
if(ArrayUtil.isBlank(parameters)){
for (int i = 0; i < parameters.length; i++) {
pst.setObject(i+1, parameters[i]);
}
}
rs=pst.executeQuery();
if(rs!=null){
ResultSetMetaData rsd=rs.getMetaData();
int columnCount = rsd.getColumnCount();
while(rs.next()){
Map<String,Object> row=new HashMap<String, Object>();
for (int i = 0; i < columnCount; i++) {
String columnName=rsd.getColumnName(i+1);
row.put(columnName, rs.getObject(columnName));
}
table.add(row);
}
}
} catch (Exception e) {
// TODO: handle exception
}finally{
closeObject(rs,pst,conn);
}
return table;
}
}