Home Tutorial Java Core Files Insert file data into database

 
 

Share on Google+Share on Google+
Insert file data into database
Posted on: April 25, 2006 at 12:00 AM
Advertisement
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.io.*;
import java.sql.*;
import java.util.*;

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

			BufferedReader br = new BufferedReader(new FileReader(
					"C:/school.txt"));
			String strLine;
			ArrayList list = new ArrayList();
			while ((strLine = br.readLine()) != null) {
				list.add(strLine);
			}
			Iterator itr;
			for (itr = list.iterator(); itr.hasNext();) {
				String str = itr.next().toString();
				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) {
		}
	}
}
Advertisement

Related Tags for Insert file data into database:


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 25, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com