Read .CSV file data and store into the database by checking whether data is present or not
Read .CSV file data and store into the database by checking whether data is present or not in java
public class ReadCsv {
public static void main(String[] args) {
String selectQuery="SELECT * FROM student";
String sql = "INSERT INTO student(id, name) VALUES (?, ?)";
Map<Integer,ArrayList<ResultSet>> map=new HashMap<Integer, ArrayList<ResultSet>>();
ArrayList<Student> students=readCSV();
PreparedStatement statement = null;
Connection con = dbconnection();
try {
statement = con.prepareStatement(sql);
Statement stmt=con.createStatement();
ResultSet res=stmt.executeQuery(selectQuery);
ArrayList<ResultSet> resdata=new ArrayList<ResultSet>();
while(res.next()) {
map.put(res.getInt("Id"), resdata);
}
for (Student record : students) {
if(!map.containsKey(record.getStudentId())) {
statement.setInt(1, record.getStudentId());
statement.setString(2, record.getStudentName());
statement.addBatch();
}
}
statement.executeBatch();
con.commit();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static ArrayList<Student> readCSV() {
String csvFilePath = "C:/Users/annap/Desktop/Student.csv";
ArrayList<Student> students=new ArrayList<Student>();
try {
BufferedReader lineReader = new BufferedReader(new FileReader(csvFilePath));
CSVParser records = CSVParser.parse(lineReader, CSVFormat.EXCEL.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());
for (CSVRecord record : records) {
Student student = new Student();
student.setStudentId(Integer.parseInt(record.get(0)));
student.setStudentName(record.get(1));
students.add(student);
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return students;
}
public static Connection dbconnection() {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentinfo?", "root", "root");
System.out.println("connection sucessfull");
connection.setAutoCommit(false);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
}
Leave a Comment