If you require a variable throughout the class, you might want to make it a member variable.
However, this is discouraged for resources like Connections
, because it can easily deprive a system, as well as put extra load.
What you can do is use a design pattern called Singleton
. Read about it here.
Basically, you can create a new class called ConnectionManager
with this implementation
class ConnectionManager {
private static ConnectionManager _instance = null;
private Connection con = null;
protected ConnectionManager() {
//empty
}
private void init() {
Class.forName("com.mysql.jdbc.Driver").newInstance();
this.con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/kamal","root","root");
}
public Connection getConnection() {
return this.con;
}
public static ConnectionManager getInstance() {
if(_instance == null) {
_instance = new ConnectionManager();
_instance.init();
}
return _instance;
}
}//end class
Now, this helps us in a number of ways, especially if your application is multi-threaded. We only need to make one connection, which will remain unless the program has been terminated. Everywhere you need to create a new Statement
, you can simply use this.
ConnectionManager.getInstance().getConnection().createStatement();