Read Data from mysql --store in text file

/*
@Author: M. Lakshmikar Reddy
@Designation: Software Engineer
@Date:22/07/2011
*/
import java.io.*;
import java.sql.*;
import java.util.ArrayList;

// used to read the data from db then write to text file

public class FileWrite{
public static void main(String[] args)throws IOException{
Writer output = null;
File file = new File(args[0]);
ArrayList al = new ArrayList();
try{
//Load the mysql driver
Class.forName("com.mysql.jdbc.Driver").newInstance();
//Get the connection
Connection con= DriverManager.getConnection("jdbc:mysql://localhost/test","root","root");
Statement stmt = con.createStatement();
// To Check the User_name field in Database if It is exist then it will update other wise it will insert the record.
ResultSet rs = stmt.executeQuery("select * from emp");


while(rs.next())
{
String text = rs.getString("USER_NAME")+" "+rs.getString("PASS_WORD")+" "+rs.getString("EMP_ID");
al.add(text);


}
output = new BufferedWriter(new FileWriter(file));
String header ="Name Password Email-Id"+"\n";
output.write(header);
for(int i=0;i output.write(al.get(i).toString()+"\n");
}
output.close();
}catch(Exception e){

e.printStackTrace();
System.err.println("Error: " + e.getMessage());
}

}
}

No comments: