Share on Google+Share on Google+

Insert file data into database

In this section, you will learn how to insert the file data into database.

Insert file data into database

In this section, you will learn how to insert the file data into database.

Description of code:

Here we have used FileReader and BufferedReader class to read the file. The data of the file is then stored into the ArrayList. To retrieve the data from the arraylist, we have used Iterator class that iterates the list value and differentiates the data of the file. Now to insert this data into the database, we have established a database connection. Then using the insert query, we have inserted whole file data into the database.

Here is the school.txt:

21  AA  87  A 
22  BB   99  A+ 
23  CC   75  A 
24  DD  55  C 
25  EE   68  B

Here is the code:

import java.sql.*;
import java.util.*;

public class InsertFileData {
	public static void main(String[] args) {
		try {
			Connection con = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/register", "root", "root");
			Statement st = con.createStatement();

			BufferedReader br = new BufferedReader(new FileReader(
			String strLine;
			ArrayList list = new ArrayList();
			while ((strLine = br.readLine()) != null) {
			Iterator itr;
			for (itr = list.iterator(); itr.hasNext();) {
				String str =;
				String[] splitSt = str.split(" ");
				String id = "", name = "", marks = "", grade = "";
				for (int i = 0; i < splitSt.length; i++) {
					id = splitSt[0];
					name = splitSt[1];
					marks = splitSt[2];
					grade = splitSt[3];
				int k = st
						.executeUpdate("insert into student(id,name,marks,grade) values('"
								+ id
								+ "','"
								+ name
								+ "','"
								+ marks
								+ "','"
								+ grade + "')");
		} catch (Exception e) {



Posted on: April 25, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial 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.


Advertisement null