0

I have a question regarding Java when fetching data from, lets say MySQL database. As of now I need to write quite a lot of redundant code when fetching data. And I wonder if there is a better way to do that.

E.g. I have an method which fetch data from a table A. The method for that will look something like this then

public void readDataBase() throws Exception {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connect = DriverManager
                    .getConnection("jdbc:mysql://localhost/feedback?"
                            + "user=sqluser&password=sqluserpw");

            statement = connect.createStatement();
            resultSet = statement
                    .executeQuery("select * from FEEDBACK.COMMENTS");
            writeResultSet(resultSet);              

        } catch (Exception e) {
            throw e;
        } finally {
            close();
        }

    }

I wonder if there's a better way to write a method such as this one. Because it gets quite ugly when you have to write code such as this, namely that you have to write those line to getConnection all the time in every method that fetch data from the database.

1
  • Exscuse me, Do you think to refactor source code? can you see documentation on wikipedia on Code Refactoring Commented Apr 15, 2011 at 20:08

7 Answers 7

1

Use Spring, with MyBatis or spring-jdbc for data access instead of raw JDBC.

spring-jdbc is a library wrapping basic JDBC code where you can provide callbacks to specify how you want resultsets mapped to objects and such. Mybatis is a little higher-level, you specify your queries in an xml file.

With Spring the big win is you get declarative transactions so you have no code starting and committing transactions, you also get templates for data access objects, and setting up a connection pool is easy. And there are plenty of examples for how to put the pieces together.

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

Comments

0

At some point you're better off writing your own DAO which handles all the plumbing for you.

Comments

0

I would do different things depending on whether I am in a single threaded batch job or inside a container.

For single threaded batch job:

  • create just one connection and reuse it
  • create just one prepared statement and reuse it
  • optimize commit calls

For J2EE

  • use the container managed data source pool

Comments

0

Most of the times when you write a program working with a database you do not open a connection every time you want to do something with it. Instead you open a connection at the beggining of the program and then use it every time when accessing a database.

Take a look at this example (pseudocode!):

class Database {

    private Connection conn;

    public Database() {
        connect();
    }

    private void connect() {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection(dbUrl);
    }

    public void close() {
        conn.close();
    }

    private ResultSet readSth() {
        statement = conn.createStatement();
        return statement.executeQuery("select * from FEEDBACK.COMMENTS");
    }

    private void doSth() {
        // do sth else with conn
    }

}

2 Comments

Isn't it a bad practice to share a single connection? Connections should be coming out of a connection pool
Hey, this is just very simple code snippet. I am waiting for you answer with a connection pool example.
0

You can create a class having static method there, that returns you an instance of connection like below:

import java.sql.*;
import java.util.Properties;

public class Getconnection{
    private static final String dbClassName = "com.mysql.jdbc.Driver";
    private static final String CONNECTION ="jdbc:mysql://127.0.0.1/dbUserData";
    private static Properties p = new Properties();
    public static Connection getConnection(){
        p.put("user","root");
        p.put("password","library");
        try{
            Class.forName(dbClassName);
            Connection con=DriverManager.getConnection(CONNECTION,p);
            return con;
        }
        catch(Exception ie){
            ie.printStackTrace();
            return null;
        }
    }
}

So that you do not need to create different instances of connection, and change only at one place if you want to...

Comments

0

I think you are suffering from basic code organization. For example, you should only create the connection once and then pass it around to whatever methods need it. Typically, people use connection pools so that only a certain number of connections ever exist to the db (because they are expensive) and a connection pool manager will loan them out as needed and keep track of their states. There are a few connection pool libraries in Java (Apache has one) but I have had good luck using: http://sourceforge.net/projects/c3p0/

I dont really like heavy ORMs such as Hibernate but I do I like MyBatis. It lets me wright SQL and doesnt inject itself all over my domain models: http://www.mybatis.org/java.html I think you would benefit greatly by having a Data Access Object layer (DAO). This layer abstracts out communication with your data so the layers above can just fetch collections of data without worrying about the underlying SQL it took to generate that list.

Comments

0

I've moved away from direct JDBC access since I started using ORM (eg. Hibernate). Or why dont you have some publicly available static method to read from the db:

public ResultSet readDataBase(String query) throws Exception {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connect = DriverManager
                    .getConnection("jdbc:mysql://localhost/feedback?"
                            + "user=sqluser&password=sqluserpw");

            statement = connect.createStatement();
            return statement.executeQuery(query);

        } catch (Exception e) {
            throw e;
        } finally {
            close();
        }

    }

and you can have similar methods when you do update/delete, etc

Comments

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.