Saturday, 2 April 2016

Read Data from Database and Store it into file by using JAVA

For this program, you must have basic knowledge of I/O and JDBC. We will use JDBC for reading data from database table. And  I/O,  for writing that data into a file.
Note: Here we used PostgreSQL JDBC (postgresql-9.4.1208.jre6.jar). PostgreSQL is a powerful, open source object-relational database system. Download postgresql-(VERSION).jdbc.jar
Create a table in database which you want to read. Here we created VOUCHER table in database.
Steps:
2. Create Connection with database.
3. Retrieve data into ResultSet. 
4. Create a file using FILE class if file doesn't exists.
5. Use FileOutputStream for opening the file in append mode.
6. Use ResultSet's next() method for reading data from database.
7. By using PrintWriter Class, we copy that data into file.

Complete Java Program:

public class jdbcMain {

          public static void main(String[] args) {
                  
                   try {                     
                            
Connection c=DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "dbname", "dbpassword");
Statement s=c.createStatement();
ResultSet rs=s.executeQuery("select voucher_no,sys_creation_date,voucher_status from voucher where voucher_no<2000;");
         
File file=new File("FreeVoucher.txt");
PrintWriter pw=new PrintWriter(new FileOutputStream(file, true));
try {
                                     
if (!file.exists()) {
          file.createNewFile();
}
                                     
                                      while (rs.next()) {
                                                pw.print(rs.getInt("voucher_no")+" ");
                                                pw.print(rs.getDate("sys_creation_date")+" ");
                                                pw.println(rs.getString("voucher_status"));
                                               
                                               
                                      }
                                      pw.println();
                                     
                                     
                             } catch (IOException e) {
                                      // TODO Auto-generated catch block
                                      e.printStackTrace();
                             }
                             finally {
                                      pw.flush();
                                      pw.close();
                             }
                   } catch (Exception e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
                   }
                   }}
/********************* END of PROGRAM ******************************/

After running this program, file FreeVoucher.txt will have all the voucher's details.




No comments:

Post a Comment