简体   繁体   中英

Re-using Connections and Statements

I have a switch-statement block of code and I want to use a reference to the connection and Statement objects. I get an error when I use the code below; Am I missing something? Should this be inside each method? Error is "try" is an invalid modifier and constructor headname excpected

  public class ClassSelectorApp {
        try{
        public static final Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ClassSelector?autoReconnect=true&useSSL=false", "", "");
        Statement myStmt = con.createStatement();
        }
        catch(java.sql.SQLException SQL) {
              SQL.printStackTrace();
            }

You need it inside of a method but if you want to re-use the connection variable try it like this

public class ClassSelectorApp 
{
    public static Connection con;

    public ClassSelectorApp()
    {
        //insert the TRY AND CATCH STUFF
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ClassSelector?autoReconnect=true&useSSL=false", "", "");
    }

    public void someMethod()
    {
        //Most likely need some try catch here also.
        Statement myStmt = con.createStatement();
    }

    public static void main(String[] args)
    {
        //Create an object of your class and invoke a method. 
        ClassSelectorApp a = new ClassSelectorApp();
        a.someMethod();
    }

}

Connections generally are not re-usable - you use them for a while, then close them and throw away the reference. To make a 'Connection' reference visible across multiple methods you can make it a member variable and initialize it in what is appropriately called an "initializer". Look up "static initializer" (sometimes WRONGLY called a "static block") and "constructor" for initialization of class and instance member variables, respectively.

public class Foo
{
  private Connection cxn;
  {
    try {
      cxn = DriverManager.getConnection(
      "jdbc:mysql://localhost:3306/ClassSelector?autoReconnect=true&useSSL=false",
       "", "");
    }
    catch( SQLException exc )
    {
      logger.error(exc.getLocalizedMessage());
      throw new IllegalStateException(exc);
    }
  }
  ...
  public void actConnected()
  {
    Statement myStmt = cxn.createStatement();
    . . . 
  }
}

I showed the 'Statement' as a local variable to point out that you don't put 'public' or 'static' on those.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM