首页 > 代码库 > Java druid
Java druid
1、ConnectionFactory
(添加引用:druid-1.0.1.jar)
package nankang.test;import java.sql.Connection;import com.alibaba.druid.pool.DruidDataSource;public class ConnectionFactory { private static DruidDataSource dataSource = null; static { try { String driver = "oracle.jdbc.driver.OracleDriver"; String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl"; String user = "phonesurvey"; String password = "world"; dataSource = new DruidDataSource(); dataSource.setDriverClassName(driver); dataSource.setUrl(url); dataSource.setUsername(user); dataSource.setPassword(password); dataSource.setInitialSize(5); dataSource.setMinIdle(1); dataSource.setMaxActive(10); dataSource.setPoolPreparedStatements(false); } catch (Exception e) { e.printStackTrace(); } } public static synchronized Connection getConnection() { Connection conn = null; try { conn = dataSource.getConnection(); } catch (Exception e) { e.printStackTrace(); } return conn; }}
2、使用
package nankang.test;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;public class Main { /** * @param args */ public static void main(String[] args) { Connection conn = null; PreparedStatement pstm = null; ResultSet rs = null; try { conn = ConnectionFactory.getConnection(); String sql = "select * from Agent"; pstm = conn.prepareStatement(sql); rs = pstm.executeQuery(); while (rs.next()) { String agentId = rs.getString("AgentId"); System.out.println(agentId); } System.out.println("成功"); } catch (Exception e) { System.out.println(String.format("失败,%s", e.getMessage())); } finally { if (rs != null) { try { rs.close(); } catch (Exception e) { e.printStackTrace(); } } if (pstm != null) { try { pstm.close(); } catch (Exception e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (Exception e) { e.printStackTrace(); } } } }}
Java druid
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。