dimanche 4 octobre 2015

Java and database Connection. Which connection class is better and why? Code inserted

I am using java and some database(oracle/sql) to store some information. So i decided to create a fixed class which will handle my connection and i shall return a con object at the end so i can use it in another classes. The main thing i have this classes is to be able to establish a connection to database from another class.

Please tell me which one is better and why and if it can be improved.

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

public class ConnectDB {

    private static ConnectDB con = new ConnectDB();


    private ConnectDB() {
        try {
               Class.forName("oracle.jdbc.driver.OracleDriver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public Connection createCon() {
        Connection connection = null;
        try {

            connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","yy","yy");

        } catch (SQLException e) {
            System.out.println("Connection to db could not be done");
        }
        return connection;
    }

    public static Connection getConexiune() {
        return con.createCon();
    }
}

or i can use this class

import java.sql.*;


public class ConectDB {
        static   Connection con;

      public static Connection getConexiune() {
        return con;
    }  

    public static void main(String arg[])
    {

        try{
        Class.forName("oracle.jdbc.driver.OracleDriver");

         con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","yy","yy");
        System.out.println("cONNECTED");

        con.close();



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





    }   


}

which one is better and why?

Does first example use Singleton design pattern?

Aucun commentaire:

Enregistrer un commentaire