Header Ads

  • Breaking Now

    How do you establish database connection using JDBC?

    The database connection using JDBC involves two steps:
    - Loading database driver class
    - Making the connection to database
    Here is code snippet for connection to the database:

    String driverClassName="sun.jdbc.odbc.JdbcOdbcDriver";
    String url="jdbc:odbc:dsnname";
    String usrname="hello";
    String passwd="india";
    String qry="select username from users";
    try{
    Class.forName(driverClassName);//loading the database driver
    Connection con=DriverManager.getConnection(url,usrname,passwd);
    Statement stmt=con.createStatement();
    ResultSet rs =stmt.executeQuery(qry);
    while(rs.next()){

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

    2 comments:

    1. some experts recommend to use DataSource for DataBase handling.

      So What is the difference b/w DataSource and DriverManager ?

      ReplyDelete
    2. DataSource object identifies and describes data source it represents. DataSource has JNDI connection so it has a separation here from creation and its application perspective. The vendor specific implementation of DataSource is provided in JDBC2.0 and 3.0 onwards.

      The JNDI description of DataSource ensures not to hard code driver information for accessing database unlike DriverManager.

      The implementation of DataSource interface can be customized to incorporate features like connection pooling and distributed transactions.

      You can get more detailed information

      here

      ReplyDelete

    Post Top Ad

    Post Bottom Ad