一、前言
这边基于DriverManager.getConnection获取数据库连接,并通过连接prepareStatement、prepareCall等方法对常用sql更新查询、blob大数据字段读写(call p_write_blob的写入blob)等常用数据操作,具体代码如下所示
二、代码
1.DBProperties配置类
jdbc.1.driver=oracle.jdbc.driver.OracleDriver@b@jdbc.1.url=jdbc:oracle:thin:@127.0.0.1:1521:xwood @b@jdbc.1.username=test@b@jdbc.1.password=test
import java.io.InputStream;@b@import java.util.Properties;@b@@b@public class DBProperties {@b@ @b@ private static Properties config = new Properties(); // 单例@b@@b@ // 类加载时通过类加载器读取类路径下的配置文件@b@ static {@b@ try {@b@ InputStream in = DBProperties.class.getClassLoader().getResourceAsStream("db.properties");// 通过类加载器获得类路径下该属性文件的一个输入流@b@ config.load(in);// 从输入流中读取属性列表@b@ in.close();@b@@b@ } catch (Exception e) {@b@ e.printStackTrace();@b@ }@b@ }@b@@b@ public static String getString(String key) {@b@ return config.getProperty(key);@b@ }@b@@b@@b@ public static String getString(String key, String defaultValue) {@b@ return config.getProperty(key, defaultValue);@b@ }@b@@b@ public static Properties getInstance() {@b@ return config;@b@ }@b@@b@ public static void main(String[] args) {@b@ System.out.println(DBProperties.getString("uploadDataPort"));@b@ }@b@@b@}
2.DBUtil工具类
import java.io.InputStream;@b@import java.io.OutputStream;@b@import java.io.Reader;@b@import java.sql.Blob;@b@import java.sql.CallableStatement;@b@import java.sql.Clob;@b@import java.sql.Connection;@b@import java.sql.DriverManager;@b@import java.sql.PreparedStatement;@b@import java.sql.ResultSet;@b@import java.sql.ResultSetMetaData;@b@import java.sql.SQLException;@b@import java.sql.Statement;@b@import java.util.ArrayList;@b@import java.util.Collections;@b@import java.util.HashMap;@b@import java.util.List;@b@import java.util.Map;@b@@b@import com.xwood.engine.common.config.DBProperties;@b@@b@public class DBUtil{@b@ @b@ protected static Connection getConnection(){@b@ String driver;@b@ try {@b@ driver = DBProperties.getString("jdbc.1.driver");@b@ String url =DBProperties.getString("jdbc.1.url");@b@ String userName =DBProperties.getString("jdbc.1.username");@b@ String password =DBProperties.getString("jdbc.1.password");@b@ Class.forName(driver).newInstance();@b@ @b@ return DriverManager.getConnection(url, userName, password);@b@ @b@ } catch (Exception ex) {@b@ ex.printStackTrace();@b@ throw new RuntimeException(ex.getMessage());@b@ }@b@ }@b@@b@ public static void close(ResultSet rs, Statement stmt, Connection conn)@b@ {@b@ if (rs != null)@b@ try {@b@ rs.close();@b@ } catch (SQLException ex) {@b@ ex.printStackTrace();@b@ }@b@@b@ if (stmt != null)@b@ try {@b@ stmt.close();@b@ } catch (SQLException ex) {@b@ ex.printStackTrace();@b@ }@b@@b@ if (conn != null)@b@ try {@b@ conn.close();@b@ } catch (SQLException ex) {@b@ ex.printStackTrace();@b@ }@b@ }@b@@b@ public static void close(ResultSet rs, Statement stmt)@b@ {@b@ close(rs, stmt, null);@b@ }@b@@b@ public static void close(Connection conn)@b@ {@b@ close(null, null, conn);@b@ }@b@@b@ public static List resultSetToList(ResultSet rs)@b@ throws SQLException@b@ {@b@ if (rs == null) {@b@ return Collections.EMPTY_LIST;@b@ }@b@@b@ ResultSetMetaData md = rs.getMetaData();@b@ int columnCount = md.getColumnCount();@b@@b@ List list = new ArrayList();@b@@b@ while (rs.next()) {@b@ Map rowData = new HashMap(columnCount);@b@ for (int i = 1; i <= columnCount; ++i)@b@ rowData.put(convertFieldName(md.getColumnName(i)), rs.getObject(i));@b@@b@ list.add(rowData);@b@ }@b@ return list;@b@ }@b@@b@ public static Map resultSetToMap(ResultSet rs)@b@ throws SQLException@b@ {@b@ if (rs == null) {@b@ return null;@b@ }@b@@b@ ResultSetMetaData md = rs.getMetaData();@b@ int columnCount = md.getColumnCount();@b@@b@ Map rowData = null;@b@ if ((rs.isFirst()) || (rs.next())) {@b@ rowData = new HashMap(columnCount);@b@ for (int i = 1; i <= columnCount; ++i)@b@ rowData.put(convertFieldName(md.getColumnName(i)), rs.getObject(i));@b@ }@b@@b@ return rowData;@b@ }@b@@b@ public static String readClob(Clob clob)@b@ throws SQLException@b@ {@b@ StringBuffer buff = new StringBuffer();@b@ try {@b@ long length = clob.length();@b@@b@ for (long p = 1L; p <= length; p += 1024L)@b@ buff.append(clob.getSubString(p, 1024));@b@@b@ return buff.toString();@b@ } catch (SQLException e) {@b@ e.printStackTrace();@b@ throw e;@b@ }@b@ }@b@@b@ public static void writeClob(Reader reader, String sTableName, String sFieldName, String sClause, Connection conn)@b@ throws Exception@b@ {@b@ String sql;@b@ PreparedStatement pst = null;@b@ CallableStatement cst = null;@b@ try@b@ {@b@ int size;@b@ sql = "update " + sTableName + " set " + sFieldName + "=EMPTY_CLOB() WHERE " + sClause;@b@ pst = conn.prepareStatement(sql);@b@ pst.executeUpdate();@b@ pst.close();@b@@b@ char[] buff = new char[4096];@b@@b@ sql = "select " + sFieldName + " from " + sTableName + " where " + sClause + " for update";@b@ cst = conn.prepareCall("{call p_write_clob(?,?,?)}");@b@ while ((size = reader.read(buff)) > 0) {@b@ cst.setString(1, sql);@b@ cst.setInt(2, size);@b@ cst.setString(3, new String(buff, 0, size));@b@ cst.execute();@b@ }@b@ } catch (Exception e) {@b@ e.printStackTrace();@b@ throw e;@b@ } finally {@b@ close(null, cst, null);@b@ close(null, pst, null);@b@ }@b@ }@b@@b@ public static void readBlob(Blob blob, OutputStream out)@b@ throws Exception@b@ {@b@ InputStream reader;@b@ try@b@ {@b@ reader = blob.getBinaryStream();@b@@b@ byte[] buffer = new byte[1024];@b@ int nbytes = 0;@b@ while ((nbytes = reader.read(buffer)) != -1)@b@ out.write(buffer, 0, nbytes);@b@@b@ reader.close();@b@ } catch (Exception e) {@b@ e.printStackTrace();@b@ throw e;@b@ }@b@ }@b@@b@ public static void writeBlob(InputStream in, String sTableName, String sFieldName, String sClause, Connection conn)@b@ throws Exception@b@ {@b@ String sql;@b@ PreparedStatement pst = null;@b@ CallableStatement cst = null;@b@ try@b@ {@b@ int size;@b@ sql = "update " + sTableName + " set " + sFieldName + "=EMPTY_BLOB() WHERE " + sClause;@b@ pst = conn.prepareStatement(sql);@b@ pst.executeUpdate();@b@ pst.close();@b@@b@ byte[] buff = new byte[15360];@b@@b@ sql = "select " + sFieldName + " from " + sTableName + " where " + sClause + " for update";@b@ cst = conn.prepareCall("{call p_write_blob(?,?,?)}");@b@ while ((size = in.read(buff)) > 0) {@b@ cst.setString(1, sql);@b@ cst.setInt(2, size);@b@ if (size == buff.length) {@b@ cst.setBytes(3, buff);@b@ } else {@b@ byte[] bytes = new byte[size];@b@ System.arraycopy(buff, 0, bytes, 0, size);@b@ cst.setBytes(3, bytes);@b@ }@b@ cst.execute();@b@ }@b@ } catch (Exception e) {@b@ e.printStackTrace();@b@ throw e;@b@ } finally {@b@ close(null, cst, null);@b@ close(null, pst, null);@b@ }@b@ }@b@@b@ public static String convertFieldName(String sName)@b@ {@b@ if (sName == null)@b@ return null;@b@@b@ if (sName.length() <= 1)@b@ return sName.toLowerCase();@b@@b@ StringBuffer dst = new StringBuffer();@b@ boolean beUpCase = false;@b@ for (int i = 0; i < sName.length(); ++i) {@b@ String tmp = sName.substring(i, i + 1);@b@ if ("_".equals(tmp)) {@b@ beUpCase = true;@b@ }@b@ else {@b@ if (beUpCase)@b@ dst.append(tmp.toUpperCase());@b@ else@b@ dst.append(tmp.toLowerCase());@b@@b@ beUpCase = false; }@b@ }@b@ return dst.toString();@b@ }@b@ @b@ @b@ public static void main(String[] args){@b@ Connection conn=DBUtil.getConnection();@b@ System.out.println("test ok!");@b@ }@b@ @b@ @b@}
3.扩展增强工具类DBUtilExt - 连接自动释放关闭等
import java.io.BufferedReader;@b@import java.sql.Connection;@b@import java.sql.PreparedStatement;@b@import java.sql.ResultSet;@b@import java.sql.SQLException;@b@import java.sql.Statement;@b@import java.util.List;@b@import java.util.Map;@b@import org.apache.log4j.Logger;@b@@b@public class DBUtilExt{@b@ @b@ public static Logger log = Logger.getLogger(DBUtilExt.class.getName());@b@ @b@ private static Connection conn = null;@b@ private static Connection conn2 = null;@b@ @b@ static{@b@ conn = DBUtil.getConnection();@b@ conn2 = DBUtil.getConnection();@b@ }@b@ @b@ public static int updateCLOB(String selectSql,String updateSql,int clobPostion,String clobValue){@b@ int retV=0;@b@ PreparedStatement ps = null;@b@ ResultSet rs = null;@b@ Statement st=null;@b@ try {@b@ conn.setAutoCommit(false);@b@ ps = conn.prepareStatement(updateSql);@b@ ps.setClob(clobPostion, oracle.sql.CLOB.empty_lob()); @b@ retV=ps.executeUpdate();@b@ st=conn.createStatement();@b@ rs = st.executeQuery(selectSql); @b@ if(rs.next()) { @b@ oracle.sql.CLOB clob = (oracle.sql.CLOB) rs.getClob(clobPostion); @b@ if(clob!=null){@b@ clob.putString(1,clobValue);@b@ }@b@ }@b@ st.close();@b@ conn.commit();@b@ }catch (Exception e) {@b@ try {@b@ conn.rollback();@b@ } catch (SQLException e1) {@b@ e1.printStackTrace();@b@ }@b@ retV=0;@b@ e.printStackTrace();@b@ }finally{@b@ try {@b@ if(ps!=null){@b@ ps.close();@b@ }@b@ } catch (Exception ee) {@b@ } @b@ @b@ }@b@ return retV;@b@ }@b@ @b@ @b@ public static String readTemCLOB(String clobName, String sqlS) throws Exception{@b@ String content=""; @b@ Statement st=null;@b@ ResultSet rs_clob=null;@b@ try {@b@ conn2.setAutoCommit(false);@b@ st=conn2.createStatement(); @b@ rs_clob=st.executeQuery(sqlS); @b@ oracle.sql.CLOB contents=null; @b@ while (rs_clob.next())@b@ { // 取出CLOB对象 @b@ contents= (oracle.sql.CLOB) rs_clob.getClob(clobName);@b@ if(contents==null)@b@ return "";@b@ BufferedReader aa = new BufferedReader(contents.getCharacterStream()); //以字符流的方式读入BufferedReader @b@ String str = ""; @b@ boolean isPre=false;@b@ while ((str = aa.readLine()) != null) { @b@ @b@ if(str.indexOf("pre class")!=-1)@b@ isPre=true;@b@ else if(str.indexOf("</pre>")!=-1)@b@ isPre=false;@b@ if(isPre){@b@ content = content.concat(str.replaceAll("<br/>", "").replaceAll("<br>", "")+"@b@");@b@ }else@b@ content = content.concat(str);@b@ @b@ @b@ }@b@ content.replaceAll("<p><br/></p>", "").replaceAll("<p><br></p>", "");@b@ @b@ }@b@ @b@ } catch (Exception e) {@b@ e.printStackTrace();@b@ }finally{@b@ if(rs_clob!=null)@b@ rs_clob.close();@b@ if(st!=null)@b@ st.close();@b@ } @b@ return StringUtil.reBackX2Sstr(content);@b@ }@b@@b@ public static int update(String sql, Object[] params, Connection conn)@b@ throws SQLException@b@ {@b@ log.info(sql);@b@ PreparedStatement pst = null;@b@ int rows = 0;@b@ try {@b@ pst = conn.prepareStatement(sql);@b@ if (params != null)@b@ for (int i = 0; i < params.length; ++i)@b@ pst.setObject(i + 1, params[i]);@b@@b@@b@ rows = pst.executeUpdate();@b@ } finally {@b@ if(pst!=null)@b@ pst.close();@b@// DBUtil.close(null, pst, null);@b@ }@b@ return rows;@b@ }@b@@b@ public static int update(String sql, Object param, Connection conn)@b@ throws SQLException@b@ {@b@ if (param instanceof Object[])@b@ return update(sql, (Object[])param, conn);@b@@b@ return update(sql, new Object[] { param }, conn);@b@ }@b@@b@ public static int update(String sql, Connection conn)@b@ throws SQLException@b@ {@b@ return update(sql, null, conn);@b@ }@b@@b@ public static int update(String sql, Object[] params)@b@ throws SQLException@b@ {@b@// Connection conn = null;@b@ try {@b@ int i;@b@// conn = DBUtil.getConnection();@b@ return update(sql, params, conn);@b@ } finally {@b@// DBUtil.close(null, null, conn);@b@ }@b@ }@b@@b@ public static int update(String sql, Object param)@b@ throws SQLException@b@ {@b@// Connection conn = null;@b@ try {@b@ int i;@b@// conn = DBUtil.getConnection();@b@ return update(sql, param, conn);@b@ } finally {@b@// DBUtil.close(null, null, conn);@b@ }@b@ }@b@@b@ public static int update(String sql)@b@ throws SQLException@b@ {@b@// Connection conn = null;@b@ try {@b@// conn = DBUtil.getConnection();@b@ return update(sql, conn);@b@ } finally {@b@// DBUtil.close(null, null, conn);@b@ }@b@ }@b@@b@ public static List query(String sql, Object[] params, Connection conn)@b@ throws SQLException@b@ {@b@ log.info(sql);@b@ PreparedStatement pst = null;@b@ ResultSet rs = null;@b@ List list = null;@b@ try {@b@ pst = conn.prepareStatement(sql);@b@ if (params != null)@b@ for (int i = 0; i < params.length; ++i)@b@ pst.setObject(i + 1, params[i]);@b@@b@ rs = pst.executeQuery();@b@ list = DBUtil.resultSetToList(rs);@b@ } finally {@b@ if(pst!=null)@b@ pst.close();@b@// DBUtil.close(rs, pst, null);@b@ }@b@ return list;@b@ }@b@@b@ public static List query(String sql, Object param, Connection conn)@b@ throws SQLException@b@ {@b@ if (param instanceof Object[])@b@ return query(sql, (Object[])param, conn);@b@@b@ return query(sql, new Object[] { param }, conn);@b@ }@b@@b@ public static List query(String sql, Connection conn)@b@ throws SQLException@b@ {@b@ return query(sql, null, conn);@b@ }@b@@b@ public static List query(String sql, Object[] params)@b@ throws SQLException@b@ {@b@ Connection conn = null;@b@ try {@b@ List localList;@b@// conn = DBUtil.getConnection();@b@ return query(sql, params, conn);@b@ } finally {@b@// DBUtil.close(null, null, conn);@b@ }@b@ }@b@@b@ public static List query(String sql, Object param)@b@ throws SQLException@b@ {@b@// Connection conn = null;@b@ try {@b@ List localList;@b@// conn = DBUtil.getConnection();@b@ return query(sql, param, conn);@b@ } finally {@b@// DBUtil.close(null, null, conn);@b@ }@b@ }@b@@b@ public static List query(String sql)@b@ throws SQLException@b@ {@b@// Connection conn = null;@b@ try {@b@// conn = DBUtil.getConnection();@b@ return query(sql, conn);@b@ } finally {@b@// DBUtil.close(null, null, conn);@b@ }@b@ }@b@@b@ public static Map querySingle(String sql, Object[] params, Connection conn)@b@ throws SQLException@b@ {@b@ log.info(sql);@b@ PreparedStatement pst = null;@b@ ResultSet rs = null;@b@ Map map = null;@b@ try {@b@ pst = conn.prepareStatement(sql);@b@ if (params != null)@b@ for (int i = 0; i < params.length; ++i)@b@ pst.setObject(i + 1, params[i]);@b@@b@@b@ rs = pst.executeQuery();@b@ map = DBUtil.resultSetToMap(rs);@b@ } finally {@b@// DBUtil.close(rs, pst, null);@b@ }@b@ return map;@b@ }@b@@b@ public static Map querySingle(String sql, Object param, Connection conn)@b@ throws SQLException@b@ {@b@ if (param instanceof Object[])@b@ return querySingle(sql, (Object[])param, conn);@b@@b@ return querySingle(sql, new Object[] { param }, conn);@b@ }@b@@b@ public static Map querySingle(String sql, Connection conn)@b@ throws SQLException@b@ {@b@ return querySingle(sql, null, conn);@b@ }@b@@b@ public static Map querySingle(String sql, Object[] params)@b@ throws SQLException@b@ {@b@ Connection conn = null;@b@ try {@b@ Map localMap;@b@// conn = DBUtil.getConnection();@b@ return querySingle(sql, params, conn);@b@ } finally {@b@ DBUtil.close(null, null, conn);@b@ }@b@ }@b@@b@ public static Map querySingle(String sql, Object param)@b@ throws SQLException@b@ {@b@// Connection conn = null;@b@ try {@b@ Map localMap;@b@// conn = DBUtil.getConnection();@b@ return querySingle(sql, param, conn);@b@ } finally {@b@// DBUtil.close(null, null, conn);@b@ }@b@ }@b@@b@ public static Map querySingle(String sql)@b@ throws SQLException@b@ {@b@// Connection conn = null;@b@ try {@b@// conn = DBUtil.getConnection();@b@ return querySingle(sql, conn);@b@ } finally {@b@// DBUtil.close(null, null, conn);@b@ }@b@ }@b@ @b@ @b@ public static void main(String[] args){@b@ List list=null;@b@ try {@b@ list= DBUtilExt.query(" ");@b@ } catch (Exception e) {@b@ // TODO Auto-generated catch block@b@ e.printStackTrace();@b@ }@b@ System.out.println("test succss!!!");@b@ }@b@ @b@ @b@}