Home Tutorial Java Core Files Insert database values in the file

 
 

Share on Google+Share on Google+
Insert database values in the file
Posted on: April 22, 2006 at 12:00 AM
Advertisement
n this section, you will learn how to retrieve the data from the database and insert into the file.

Insert database values in the file

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.

Advertisement

Related Tags for Insert database values in the file:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 22, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com