0

I wrote a Java class for running MS Sql queries inside my program. This program make a new connection for each query that should be run. I know that this can increase my latency. Here is the calss code:

import java.sql.*;

public abstract class DatabaseManager {

    public static ResultSet executeQuery(String SQL, String dbName)
    {
        ResultSet rset = null ;
        try {
               Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
               String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
                  "databaseName="+dbName+";user=??;password=??;";
               Connection con = DriverManager.getConnection(connectionUrl);
               Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
               rset = st.executeQuery(SQL);
               //st.close();
        }
        catch (ClassNotFoundException e) {}
        catch (SQLException e) {}
        return rset;
     }

    public static void executeUpdate(String SQL, String dbName)
    {
        try {
               Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
               String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
                  "databaseName="+dbName+";user=??;password=??;";
               Connection con = DriverManager.getConnection(connectionUrl);
               Statement st = con.createStatement();
               st.executeUpdate(SQL);
               st.close();
               con.close();
        }
        catch (ClassNotFoundException e) {System.out.println(e);}
        catch (SQLException e) {System.out.println(e);}
     }
}

How can I change in the way that just one connection is created and all my queries route throught that connection? Regards.

4

3 Answers 3

4

I beg to differ, I would not declare a database connection as a singleton. The usual approach is to cache a pool of managed database connections. The advantages here are:

  • More concurrent access to the database
  • Managed disposal of the database resources (connection pool shrinking if necessary)

Have a look at this

http://en.wikipedia.org/wiki/Connection_pool

The usual implementations are http://sourceforge.net/projects/c3p0/ http://commons.apache.org/proper/commons-dbcp/

If you deploy your applications in a commercial application server, such as Websphere or Weblogic, they come with out-of-the-box support for database connection pooling

Sign up to request clarification or add additional context in comments.

4 Comments

What is the best implementation for that?
It depends on your environment. In my experience, I have used the database connection pooling which the application servers gave me, but when I have had software delivered by providers, they were quite happy with DBCP.
I found out that MS SQL Server support connection pooling from inside. Do you have any information how can i use that?
I am very sorry, I know nothing about that particular product :( However, if it works for you, then it's OK :) Just consider how attached you finish to your database implementation with that solution, and if a solution like DBCP would decouple you from future database provider changes
1

You must implement Singleton pattern. It similar to below:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {
    private static Connection connection = null;
    private static Class driver;
    public static void loadDriver() throws ClassNotFoundException{
        driver = Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 
    }
    /**
     * Check for some connection
     * @return true, eсли установленно; false в противном случае
     */
    public static boolean isConnection(){
        if (connection != null) return true;
        return false;
    }
    /**
     * Return connection
     */
    public static synchronized Connection getConnection(String url,
            String user, String pass) throws SQLException{
        //Create connections if we have't work connection.
        if (connection == null || connection.isClosed()) {
            connection = DriverManager.getConnection(url, user, pass); //Next string show use without parameters
            //connecction = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;" +
              "databaseName="+dbName+";user=??;password=??;";);
            connection.setAutoCommit(false);
        }
        return connection;
    }
}

You can use it:

try{
      DBConnection.loadDriver();
      conn = DBConnection.getConnection(dburl, dbuser, dbpass);
//get Prepared statement and Result set. You cam create many anstances from one connections.
      PreparedStatement ps = null; ResultSet rs = null;
      ps =  conn.prepareStatement("Some query");
      rs = ps.executeQuery();
} catch (SQLException sqlex) {System.out.println("SQL problem");}
finally{ //You can close all connections
        rs.close();
        ps.close();
        //Close DB connections before terminate code.
        conn.close()
}

1 Comment

That is only a solution if there is no multithreading, and it is no problem if the connection times out and breaks. Otherwise: use a connection pool and open a connection when needed and close when you have completed a unit of work.
0

You should implement singleton pattern to get a single instance of a class, that handle all your query request. Here is an example Connect to Database with JDBC, Singleton

1 Comment

Another option is to autowire your JDBCConnection through Spring. In that case you also reuse your same connection...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.