Tuesday, May 22, 2007

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";
Class.forName(driverClassName);//loading the database driver
Connection con=DriverManager.getConnection(url,usrname,passwd);
Statement stmt=con.createStatement();
ResultSet rs =stmt.executeQuery(qry);

} catch(Exception exc){


Vivek on May 22, 2010 at 5:17 AM said...

some experts recommend to use DataSource for DataBase handling.

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

Deepun on May 22, 2010 at 9:53 AM said...

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



Interview Questions On Java,Java EE Copyright © 2017. Reads: best tracker