Insert text file data into Database


 

Insert text file data into Database

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

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

Insert text file data into Database

In this section, you will learn how to insert the text file data into the database. For this purpose, we have created a 'student.txt' file consisting of students information i.e, id, name, course and department. Now to read this file, we have used DataInputStream and transfer the data to the ArrayList. This list is then iterated through the Iterator interface. After that we have used split() method to break the string data. This data is then inserted into the database.

Here is the student.txt:

1       A       MCA      ComputerScience
2       B       Btech       Mechanical
3       C       Btech       Electrical
4       D       MBA       Management
5       E        LLB        Law
6       F        MBBS    MedicalScience

Here is the code of InsertFileData.java:

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();

FileInputStream fstream = new FileInputStream("C:\\Answers\\Swing\\student.txt");
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    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="",course="",deptt="";
      for (int i = ; i < splitSt.length ; i++) {
         id=splitSt[0];
     name=splitSt[1];
     course=splitSt[2];
     deptt=splitSt[3];
    }

int k=st.executeUpdate("insert into student(id,name,course,department) values
('"
+id+"','"+name+"','"+course+"','"+deptt+"')");
    
}
}
catch(Exception e){}
}
}

Ads