Insert file data into database


 

Insert file data into database

In this section, you will learn how to insert the 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.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) {
		}
	}
}

Ads