大家好:
一個JAVA新手的作業卡關問題
我的程式碼如下:
public class Test {
	public static void main(String[] args) throws IOException, SQLException {
		HikariCpUtill connPool = new HikariCpUtill();
		Test read = new Test();
		try {
			HikariDataSource ds = connPool.openDataSource();
			Connection conn = ds.getConnection();
			String sqlStr = "SET IDENTITY_INSERT Topic ON "
					+ "INSERT Topic(id ,number ,name ,CEO ,phone ,address) VALUES(?,?,?,?,?,?)";
			PreparedStatement preState = conn.prepareStatement(sqlStr);
			boolean status = !conn.isClosed();
			if (status) {
				System.out.println("Connection ststus: " + status);
			}
			ArrayList<String> List = read.getData();
			
			String[] str = List.get(0).split(",");
			
			preState.setInt(1, Integer.valueOf(str[0]));
			preState.setString(2, str[1]);
			preState.setString(3, str[2]);
			preState.setString(4, str[3]);
			preState.setString(5, str[4]);
			preState.setString(6, str[5]);
			
			int insertCount = preState.executeUpdate();
			System.out.println("insertCount: " + insertCount);
			preState.close();
			conn.close();
			System.out.println("Close Connection!!");
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			connPool.closeDateSource();
			System.out.println("Close HikariDataSource!!");
		}
	}
	public ArrayList<String> getData() throws IOException {
		String csv = "D:\\JAVA上課\\產險會員名錄.csv";
		ArrayList<String> list = new ArrayList<String>();
		File file = new File(csv);
		FileInputStream fis = new FileInputStream(file);
		InputStreamReader isr = new InputStreamReader(fis, "UTF8");
		BufferedReader br = new BufferedReader(isr);
		String line;
		  while ( (line = br.readLine()) != null){
	             list.add(line);
		  }
		
		  list.remove(0);
		return list;
	}
}
如何讓List.get(0).split(",");的 (0)可以從0一直讀到List.size()的總數
不用一直輸入0->1->2->3選擇的行才讀入SQL
            String[] str = List.get(0).split(",");
			
            preState.setInt(1, Integer.valueOf(str[0]));
			preState.setString(2, str[1]);
			preState.setString(3, str[2]);
			preState.setString(4, str[3]);
			preState.setString(5, str[4]);
			preState.setString(6, str[5]);
感謝各位大神
有四種寫法
可以選一種你自己喜歡的
for (int idx = 0; idx < List.size(); idx++) { 		      
    String[] str = List.get(idx).split(",");       
    
    preState.setInt(1, Integer.valueOf(str[0]));
    preState.setString(2, str[1]);
    preState.setString(3, str[2]);
    preState.setString(4, str[3]);
    preState.setString(5, str[4]);
    preState.setString(6, str[5]);
    int insertCount = preState.executeUpdate();
    System.out.println("insertCount: " + insertCount);
}   		
另外
建議變數取名最好不要「類似」保留字以免造成混淆
什麼 read, List 這種的變數
for (int index = 0; index < List.size(); index ++) {
   String[] str = List.get(index).split(",");
   .
   .
   .
}
下面這個方法在Java是效能殺手,但在很多程式語言卻是標配:
for(String s : list){
    String[] str = s.split(",");
}