In this section, you will learn how to retrieve the data from the database and insert into the file.
Description of code:
This is a simple task. First of all we have retrieved the values from the database and stored it into arraylist. Then we have called the method writeToFile() and pass the arraylist and the file path as the parameters. This method stores the arraylist value into the specified file.
Here is the code:
import java.io.*;
import java.sql.*;
import java.util.*;
class InsertToFile {
private static void writeToFile(java.util.List list, String path) {
BufferedWriter out = null;
try {
File file = new File(path);
out = new BufferedWriter(new FileWriter(file, true));
for (String s : list) {
out.write(s);
out.newLine();
}
out.close();
} catch (IOException e) {
}
}
public static void main(String arg[]) {
java.util.List list = new ArrayList();
try {
Connection con = null;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/register", "root", "root");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("Select * from student");
while (rs.next()) {
list.add(rs.getString(1) + " " + rs.getString(2) + " "
+ rs.getString(3) + " " + rs.getString(4));
}
writeToFile(list, "student.txt");
} catch (Exception e) {
}
}
}
Through the above code, you can retrieve the values from the database and store them into the file.