I have coded a 2 private classes that use the Sql Server database in each class.
Is it possible to code a separate class (databaseConenction) that issue the connection and it is usable in the other classes?
Code:
// Create a variable for the connection string String connectionUrl ="jdbc:sqlserver://xxxxxxxxx.xxxx.xxxx.xxxx:1433;databaseName=name;user=user;password=pass"; // Declare the JDBC objects Connection con = null; // Establish the connection Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); con = DriverManager.getConnection(connectionUrl);
OK, I have to ask: why is it important you only use one connection? And if it is important, why are you not implementing this by configuing SQL Server itself?
Using the code in main, would I pass the dbHandler to the LoadFile and validateData classes? This is where the SQL is located.
Your code where:
is wrong, it should be:
Better yet, use this:
and in CHRISInterface you would do the same, just use DBHandler.getConnection() whenever you need a connection. Yes, you will need to insert try/catch to the above sample codes.
enjoy!
[ September 03, 2008: Message edited by: T.A. Nguyen ] [ September 22, 2008: Message edited by: T.A. Nguyen ]
"The field connection cannot be declared static; static fields can only be declared in static or top level types"
2. Statement s = DBHandler.getConnection.createStatement(); "Cannot make a static reference to the non-static method getConnection() from the type CHRISInterface.DBHandler"
I changed the class to static and the getConnection method to static
Is there a reason why this had to be done?
[B}public static class DBHandler { [/B] // The Instance private static Connection connection;
//Private so one can access it externally private DBHandler() { }
// Connect to DB public static Connection getConnection() { try { if (connection == null) { // Create a variable for the connection string String connectionUrl = "jdbc:sqlserver://testServer:1433;databaseName=test;" + "user=testuser;password=testpass"; // Declare the JDBC objects // Establish the conenction Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); connection = DriverManager.getConnection(connectionUrl); } } // end try catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }
Here is the complete codes for DBHandler.java, please note the I move the main (test) method inside DBHandler.java, what's missing here is the actual code for CHRISInterface... have fun.
This is a typical singleton implementation. Accessing via a static method, the method control creation/access of the class static field. Remember, this is NOT the only way...
[ September 22, 2008: Message edited by: T.A. Nguyen ]