Question

I'm trying to work with java data access, so this with what I came up with:
Tell me what do you think about this
(It's a little bit like SqlConnection from C#)

import java.sql.*;
public class SqlConnection {

    Connection connection;

    public Connection GetConnection() {return connection;}

    public void Connect(String cs, String user, String pass)
    {
         try {
                Class.forName("net.sourceforge.jtds.jdbc.Driver");      
                connection = DriverManager.getConnection(cs, user, pass);
                System.out.println("connected");

                } catch (Exception e) {         
                e.printStackTrace();
            }   
    }

    public void Disconnect() 
    {
        if(connection != null){
            try {
                connection.close();
            } catch (SQLException e){
                e.printStackTrace();
            }
            connection = null;
        }
    }
}

I think I'm going to use it like this

public class MyDAL {
public Foo[] GetFoos()
{
SqlConnection conn = new SqlConnection();
PreparedStatement comm = null;
ResultSet rs = null;
         try {
             conn.Connect(cs, user, pass);           
             comm = conn.GetConnection()
             .prepareStatement("SELECT * FROM foos");
             rs = comm.executeQuery();           
             while (rs.next()) {                    
                    String s = rs.getString("name");
                    ...
                    }         
            } catch (Exception e) {         
            e.printStackTrace();
            }
            finally
            {
                               DBUtil.Close(rs);
                               DBUtil.Close(comm);
                   conn.Disconnect();
            }
}
Was it helpful?

Solution

If you want to learn java JDBC this is fine. I'd not use capitalized method names (those are typically C#, not java) and use a logger (mostly log4j but pick your favorite flavour) instead of stdout and stderr.

Catching Exception is really bad practice; best catch all specific exceptions first so you can make a sensible error message. You can always catch Exception after that, if you really think you can get your software to function.

In this particular case I'd catch specific exceptions in Connect and throw my home build CannotConnectException(originalException). This exception is not uncommon but also not a normal flow, typical for a checked exception.

If you want to do something scalable then at least use Apache DBCP, a database connection pool in stead.

If you want to learn something used in most Java database-related applications, go for Hibernate, or EJB3 (also done by Hibernate). You really don't see too much raw JDBC applications in the wild anymore.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top