forked from youtube-arjun-codes/CsvToDatabaseJava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCSVConsume.java
More file actions
65 lines (49 loc) · 1.88 KB
/
CSVConsume.java
File metadata and controls
65 lines (49 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import static java.lang.Integer.parseInt;
public class CSVConsume {
public static void main(String[] args) {
String jdbcUrl="jdbc:mysql://localhost:3306/ems";
String username="root";
String password="";
String filePath="C:\\Users\\laser\\Desktop\\data.csv";
int batchSize=20;
Connection connection=null;
try{
connection= DriverManager.getConnection(jdbcUrl,username,password);
connection.setAutoCommit(false);
String sql="insert into employee(id,name,address,salary) values(?,?,?,?)";
PreparedStatement statement=connection.prepareStatement(sql);
BufferedReader lineReader=new BufferedReader(new FileReader(filePath));
String lineText=null;
int count=0;
lineReader.readLine();
while ((lineText=lineReader.readLine())!=null){
String[] data=lineText.split(",");
String id=data[0];
String name=data[1];
String address=data[2];
String salary=data[3];
statement.setInt(1,parseInt(id));
statement.setString(2,name);
statement.setString(3,address);
statement.setInt(4,parseInt(salary));
statement.addBatch();
if(count%batchSize==0){
statement.executeBatch();
}
}
lineReader.close();
statement.executeBatch();
connection.commit();
connection.close();
System.out.println("Data has been inserted successfully.");
}
catch (Exception exception){
exception.printStackTrace();
}
}
}