import java.sql.Connection;import java.sql.SQLException;import javax.naming.Context;import javax.naming.InitialContext;import javax.naming.NamingException;import javax.sql.DataSource;public class DBUtil { /** * 在tomcat的server.xml中配置datasource
* /*/ private static DataSource ds = null; private Connection conn; public Connection getConnection () throws Exception{ try { if (ds == null) { initDS(); } conn = ds.getConnection(); conn.setAutoCommit(false); return conn ; } catch (SQLException e) { e.printStackTrace(); throw e; } } //通过jndi获取ds private void initDS () throws Exception { try { Context initContext = new InitialContext (); Context envContext= (Context) initContext.lookup("java:/comp/env"); ds = (DataSource) envContext.lookup("jdbc/MySQL"); //return ds ; }catch (NamingException e){ e.printStackTrace(); }catch (ClassCastException e2){ e2.printStackTrace(); } }}