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();
}