JDBC串連mysql

來源:互聯網
上載者:User

標籤:

1.properties 設定檔

driver=com.mysql.jdbc.Driver#urlurl=jdbc:mysql://localhost:3306/pabitel#useruser=root#passwordpassword=493656696

 

 

2.建一個用來擷取串連的類

 1 public class DBHelper { 2     private DBHelper(){} 3     private static String url; 4     private static String driver; 5     private static String user; 6     private static String pwd; 7     private static ThreadLocal<Connection> tl=new ThreadLocal<Connection>(); 8     static{ 9         try {10             Properties prop=new Properties();11             InputStream is=DBHelper.class.getClassLoader().getResourceAsStream("properties.properties");12             prop.load(is);13             driver=prop.getProperty("driver");14             user=prop.getProperty("user");15             pwd=prop.getProperty("password");16             url=prop.getProperty("url");17             Class.forName(driver);18         } catch (Exception e) {19             e.printStackTrace();20             throw new RuntimeException(e);21         }22     }23     public static Connection getConnection() throws SQLException{24         Connection conn=DriverManager.getConnection(url,user,pwd);25         tl.set(conn);26         return conn;27     }28     public static void closeConnection(){29         Connection conn=tl.get();30         if(conn!=null){31             try {32                 conn.close();33             } catch (SQLException e) {34                 // TODO Auto-generated catch block35                 e.printStackTrace();36             }37             tl.remove();38         }39     }40 }

 

3.threadlocal的使用

其類似於map,key-value組合,key為線程,value為connection

4.線程池的使用

定義線程池private static BasicDataSource ds;

後續在靜態塊中設定如下參數

 1        ds=new BasicDataSource(); 3             ds.setDriverClassName(prop.getProperty("driver")); 4             ds.setUrl(prop.getProperty("url")); 5             ds.setUsername(prop.getProperty("user")); 6             ds.setPassword(prop.getProperty("psw")); 7             ds.setInitialSize(Integer.parseInt(prop.getProperty("initsize"))); 8             ds.setMaxActive(Integer.parseInt(prop.getProperty("maxactive"))); 9             ds.setMaxWait(Integer.parseInt(prop.getProperty("maxwait")));10             ds.setMinIdle(Integer.parseInt(prop.getProperty("minidle")));11             ds.setMaxIdle(Integer.parseInt(prop.getProperty("maxidle")));

即可用線程池來擷取串連。

 

JDBC串連mysql

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.