Holding/refreshing the MySQL-connection

Discussion in 'Plugin Development' started by Kostronor, Aug 19, 2011.

Thread Status:
Not open for further replies.
  1. Offline

    Kostronor

    Hey there,

    I'm experimenting a bit with MySQL and because of just not being so dumb and creating a new connection for every statement i want to submit, i made a global connection in my class (shown below)
    the problem is:
    if the connection is not used for some minutes, it becomes invalid.
    So i thought, why not just recreate the same connection using the same variable, nothing changed, just a refreshed connection.
    But, how does my plugin know if it should refresh the connection?
    Here is some code to show what i mean:
    Code:
    public class MySQL {
    
        private Connection cn = null;
    
        public MySQL(){
    
            try {
                Class.forName("com.mysql.jdbc.Driver");
                cn = DriverManager.getConnection( *** );
    
            } catch( Exception ex ) {
                System.out.println( ex );
                ex.printStackTrace();
            }
        }
    
        public void reconnect(){
            try {
                Class.forName("com.mysql.jdbc.Driver");
                cn = DriverManager.getConnection( *** );
    
            } catch( Exception ex ) {
                System.out.println( ex );
                ex.printStackTrace();
            }
        }
    
        public ResultSet showDbTable(String table) throws SQLException{
            Statement  st = null;
            ResultSet  rs = null;
            try {
                st = cn.createStatement();
                rs = st.executeQuery( "select * from " + table );
    
            } catch( SQLException ex ) {
                System.out.println( ex );
                ex.printStackTrace();
            }
            return rs;
        }
    Thanks for help :)
     
  2. I'd recommend using @alta189 's SQL Library.
     
  3. Offline

    Kostronor

    I've already checked the code of the library and found nothing regarding a reconnect.
    I just want to understand how this works, so I have to ask again :D
     
  4. Check the connection status and if it's closed open a connection.
     
Thread Status:
Not open for further replies.

Share This Page