提取文本文件內容保存到數據庫
步驟一:查看http://www.rzrgm.cn/hyystudy/p/8052338.html完成MySQL連接操作
步驟二:創建.txt文件,每一行為數據表中一行內容,每個字段之間用同一字符進行分隔,這里用空格,如下圖;文件保存時采用utf-8編碼格式(為防止存入數據庫,出現中文亂碼)

步驟三:在junit中進行測試:
1 @Test 2 public void linkDatabase() { 3 BaseDao dao=new BaseDao(); 4 Connection conn=dao.getConnection(); 5 Scanner input=new Scanner(System.in); 6 System.out.println("輸入文件路徑:"); 7 String filePath=input.next(); 8 boolean res=false; 9 try { 10 File file=new File(filePath); 11 FileReader fr=new FileReader(file); 12 char[] cbuf=new char[(int)file.length()]; 13 fr.read(cbuf); 14 fr.close(); 15 String[] table=new String(cbuf).split("\r\n"); 16 String[][] row=new String[table.length][]; 17 int num=0; 18 String sql="insert into topics values(?,?)"; 19 PreparedStatement stmt=conn.prepareStatement(sql); 20 for(int i=0;i<table.length;i++) { 21 row[i]=table[i].split(" "); 22 stmt.setString(1, row[i][0]); 23 stmt.setString(2, row[i][1]); 24 num+=stmt.executeUpdate(); 25 } 26 if(num>0) { 27 res=true; 28 } 29 System.out.println("文件添加成功!"); 30 } catch (FileNotFoundException e) { 31 e.printStackTrace(); 32 } catch (IOException e) { 33 e.printStackTrace(); 34 } catch (SQLException e) { 35 e.printStackTrace(); 36 } 37 }
浙公網安備 33010602011771號