package com.wondersgroup.kszx.core.db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.wondersgroup.kszx.util.ConfigUtil; public class MysqlConn { private static Connection conn; protected static Statement stmt; public static final ThreadLocal mysql_tl = new ThreadLocal(); private static final String db_ip=ConfigUtil.getProperty("DATAPUTOUT_MYSQL_IP"); private static final String db_port=ConfigUtil.getProperty("DATAPUTOUT_MYSQL_PORT"); private static final String db_sid=ConfigUtil.getProperty("DATAPUTOUT_MYSQL_SID"); private static final String db_user=ConfigUtil.getProperty("DATAPUTOUT_MYSQL_USER"); private static final String db_pwd=ConfigUtil.getProperty("DATAPUTOUT_MYSQL_PASSWORD"); private static final String db_url="jdbc:mysql://"+db_ip+":"+db_port+"/"+db_sid+"?useUnicode=true&characterEncoding=utf-8"; static{ try{ Class.forName("com.mysql.jdbc.Driver"); }catch(Exception ex){ ex.printStackTrace(); } } public MysqlConn(){ } protected synchronized void openConnection(){ try{ conn=(Connection)mysql_tl.get(); if(conn==null){ //conn.setAutoCommit(false); conn=DriverManager.getConnection(db_url,db_user,db_pwd); mysql_tl.set(conn); } }catch(Exception ex){ ex.printStackTrace(); } } private synchronized void init(){ } protected void closeConnection(){ try{ if(conn!=null){ conn.close(); mysql_tl.set(null); } }catch(Exception ex){ ex.printStackTrace(); } } protected void beginTransaction(){ try{ if(stmt==null){ stmt=conn.createStatement(); } }catch(Exception ex){ ex.printStackTrace(); } } protected boolean endTransaction(boolean commit){ try{ if(stmt!=null && conn!=null){ if(commit){ conn.commit(); stmt.close(); stmt=null; return true; }else{ conn.rollback(); stmt.close(); stmt=null; return false; } }else{ return false; } }catch(Exception ex){ ex.printStackTrace(); return false; } } public List listJdbcMysql(String sql){ List dataList = new ArrayList(); Connection conn = null; Statement stmt = null; ResultSet rs = null; ResultSetMetaData rsm = null; try { conn = DriverManager.getConnection(db_url,db_user,db_pwd); stmt = conn.createStatement(); try { rs = stmt.executeQuery(sql); rsm = rs.getMetaData(); while (rs.next()) { Map m = new HashMap(); for (int i = 1; i <= rsm.getColumnCount(); i++) { m.put(rsm.getColumnName(i), rs.getObject(i)); } dataList.add(m); } } catch (Exception e) { dataList = null; e.printStackTrace(); } } catch (Exception e) { dataList = null; e.printStackTrace(); } finally { try { if(rs != null) rs.close(); if(stmt != null) stmt.close(); if(conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return dataList; } }