Java , MySQL අවුලක්

dnet

Active member
  • Dec 14, 2010
    178
    80
    28
    VPS එකක තියන MySQL Database එකකට Java වලින් හදපු ප්‍රෝගෑම් එකක් Connect කරාම Data එන්න සෑහෙන්න වෙලාවක් යනවානේ. සමහර වෙලාවට විනාඩි 2,3 ක් විතර යනවා. Localhost එකේදී Millisecond කිහිපයකදී Data එනවා. මේ අවුල හදාගන්න ක්‍රමයක් නැද්ද?
     

    dnet

    Active member
  • Dec 14, 2010
    178
    80
    28
    Use Connection pool.

    In software engineering, a connection pool is a cache of database connections maintained so that the connections can be reused when future requests to the database are required.

    Connection pools are used to enhance the performance of executing commands on a database.


    http://stackoverflow.com/questions/24971331/mysql-jdbc-connection-takes-too-long


    Code:
      public Connection getConnection() throws Exception {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","rootpass");
            return con;
                  
            
           
        }

    ඔය තියෙන්න මගේ Code එක ඕක connection pool එකක් විදිහට හදාගන්නේ කොහොමද ?
     

    Htc1

    Junior member
  • May 15, 2015
    158
    12
    18
    Code:
      public Connection getConnection() throws Exception {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","rootpass");
            return con;
                  
            
           
        }

    ඔය තියෙන්න මගේ Code එක ඕක connection pool එකක් විදිහට හදාගන්නේ කොහොමද ?

    Code:
    javax.sql.DataSource source = new org.apache.commons.dbcp.BasicDataSource();
    source.setDriverClassName("com.mysql.jdbc.Driver");
    source.setUsername("username");
    source.setPassword("password");
    source.setUrl("jdbc:mysql://localhost:3306/myDatabase");

    Once you have a DataSource, it is easy to get a connection from the pool.

    Code:
    java.sql.Connection connection = source.getConnection();

    closing the connection will return it to the pool for you.

    Code:
    connection.close();

    got from http://stackoverflow.com/questions/2826212/need-code-to-create-connection-pool-in-java