Fetch Data from Data base by using JDBC


Required Jar files
                 1)   Mysql-connector.jar(for connecting MYSQL DB)
                 2)      Ojdbc14.jar(for Oracle DB)

Java File Name - FetchData.java

/**
 * 
 */
package com.jdbc;

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

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSet;
import com.mysql.jdbc.Statement;
/**
 * @Author -- Ramu Chintha
 */

/**
 * @author chint
 *
 */
public class FetchData {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// TODO Auto-generated method stub
Connection con = null;
Statement pstmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/ramu","root","ramu");
String sql ="SELECT * FROM BANK_ACCOUNT";
pstmt= (Statement) con.createStatement();
ResultSet rs = (ResultSet) pstmt.executeQuery(sql);
while(rs.next()){
         //Retrieve by column name
         int id  = rs.getInt("id");
         String first = rs.getString("full_name");
         int money = rs.getInt("balance");

         //Display values
         System.out.print("ID: " + id);
         System.out.print(", First: " + first);
         System.out.println(", Last: " + money);
      }
}
catch(Exception e){
e.printStackTrace();

}
finally{
// Here we will close the DB Conneciton
System.out.println("Connection is closing");
if(con != null){
con.close();
}
}

}
}



0 comments:

Post a Comment