How to fetch data from the database

There are several methods to fetch data from the Database.  Out of which I personally  prefer DNS less connectivity (JDBC Type 4), as its very easy and handy for any user.

The JDBC type 4 driver, also known as the Direct to Database Pure Java Driver, is a database driver implementation that converts JDBC calls directly into a vendor-specific database protocol.Therefore it is called a THIN driver.

Written completely in Java, type 4 drivers are thus platform independent. They install inside the Java Virtual Machine of the client. This provides better performance  as it does not have the overhead of conversion of calls into ODBC or database API calls and it does not need associated software to work.

Now this being said lets peek into the coding part.

Here goes the code:

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

public class Main {
public static void main(String[] argv) throws Exception {

/** There are different connection string to the database which you want to connect to.  For eg,
SQL Server – “jdbc:odbc:Driver={SQLServer};Server=Your_Server_Name;Database=Your_Database_Name;Uid=Your_Username;Pwd=Your_Password;”
Microsoft Access – “jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=C:/data.MDB”
Oracle – “jdbc:odbc:Driver= {Microsoft ODBCforOracle};;Uid=Your_Username;Pwd=Your_Password;”

String myDB = “jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=C:/data.MDB”;
Connection conn = DriverManager.getConnection(myDB, “UserName”, “Password”);
ResultSet rs = stmt.executeQuery(query);

while ( {
System.out.println(rs.getString(“EmployeeID”) + ” ” + rs.getString(“LastName”) + ” ”
+ rs.getString(“FirstName”));
}catch (Exception e) {
// handle the exception
} finally {
try {

} catch (Exception ee) {


Hope this code snipped has been of your help!!!


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s