about 1 year ago
I want to insert a csv data into a MySQL table. When I run the code, I've got the following error message. Any suggestions?
java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 at BudgetTrackerCui/CSVInsert.CSVInsert.main(CSVInsert.java:44)
package CSVInsert; 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 CSVInsert { public static void main(String[] args) { String jdbcUrl="jdbc:mysql://192.168.0.45:3306/testdb"; String username="user_name"; String password="password"; String filePath="/home/user/Documents/GDP.csv"; int batchSize=20; Connection connection=null; try{ connection= DriverManager.getConnection(jdbcUrl,username,password); connection.setAutoCommit(false); String sql="insert into gdp_table(country_code,ranking,country_name,gdp) 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 country_code=data[0]; String ranking=data[1]; String country_name=data[2]; String gdp=data[3]; statement.setString(1,country_code); statement.setInt(2,parseInt(ranking)); statement.setString(3,country_name); statement.setInt(4,parseInt(gdp)); 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(); } } }
Here is a sample of the csv file.
Starting with Chrome version 45, NPAPI is no longer supported for Google Chrome. For more information, see Chrome and NPAPI (blog.chromium.org).
Firefox and Microsoft Internet Explorer are recommended browsers for websites using java applets.
Chrome Version Support
Are you sure, you want to delete this comment?
Sign up using
0 Answer(s)