如何用Java將excel數(shù)據(jù)導(dǎo)入數(shù)據(jù)庫
最近寫了點關(guān)于將excel導(dǎo)入數(shù)據(jù)庫的代碼,當(dāng)然也可以看做是對前面所介紹的小項目進行補充所做的準(zhǔn)備。
我一般都是先完成功能,然后將其封裝成塊,再添加到項目中,個人癖好不值得借鑒。項目中關(guān)于解析excel數(shù)據(jù)的方式請參考:http://blog.csdn.net/trsli/article/details/17392943
這是已經(jīng)成功插入數(shù)據(jù)化數(shù)據(jù)庫中數(shù)據(jù)的記錄,我新建的表為db. 這是在控制臺的數(shù)據(jù)輸入
很多時候拼接字符串是很多項目必須做的,該代碼中我拼接了不少sql語句,也許有更簡單的方式,但是我現(xiàn)在只能想到這一步。
/**將execl數(shù)據(jù)導(dǎo)入數(shù)據(jù)庫 * @author trsli * */ public class CreateDBTable { private static Connection conn; private static String sql=""; private static StringBuffer buf=new StringBuffer(); static{ conn=DBConnection.getConnection(); } public static void main(String[] args) { //數(shù)據(jù).xls文件路徑 System.out.println("輸入文件路徑:"); String filename=new Scanner(System.in).nextLine(); //獲取需要插入數(shù)據(jù)庫的數(shù)據(jù)內(nèi)容 Object[][] contents=new PoiUtil().getmessage(filename); //獲取數(shù)據(jù)庫創(chuàng)建表格的字段名 Object[] titles=new PoiUtil().gettitles(filename); System.out.println("輸入數(shù)表格名:"); String fname=new Scanner(System.in).nextLine(); try { String ziduan=""; String blank=""; PreparedStatement stmt=conn.prepareStatement(sql); buf.append("create table "+fname+"( id int primary key auto_increment"); //拼接字符串,主要是為了完全實現(xiàn)動態(tài)創(chuàng)建數(shù)據(jù)表格以及后期插入數(shù)據(jù) <span style="color:#ff6666;">for(int i=0;i<titles.length;i++){ buf.append(","+titles[i]+" varchar(20)"); if(i==titles.length-1){//字符串末尾沒有“,” ziduan+=titles[i]+""; blank+="?"; }else{ ziduan+=titles[i]+","; blank+="?,"; } } </span> //sql數(shù)據(jù)拼裝完成 sql="insert into "+fname+"("+ziduan+") values ("+ blank+")"; buf.append(" );"); stmt.executeUpdate(buf.toString()); System.out.println("預(yù)處理..."); try { Thread.sleep(2000);//用于保證數(shù)據(jù)庫建表操作完成 System.out.println("建表成功..."); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } <span style="color:#ff6666;">for(int i=0;i<contents.length;i++){ Object[] content=contents[i];//獲取一行數(shù)據(jù) PreparedStatement insert=conn.prepareStatement(sql); for(int j=0;j<content.length;j++){ insert.setString(j+1, content[j].toString());//預(yù)加載數(shù)據(jù) } insert.executeUpdate();//插入數(shù)據(jù) System.out.println("第"+i+"行成功..."); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } </span> } System.out.println("插入數(shù)據(jù)完成"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } |
整個代碼很簡單,可以從中提取出需要的方法,用于其它需要的地方,而這就是未來需要做的。個人感覺還有許多需要改進的地方,當(dāng)然自從開始研究POI以來,我還沒有對其進行更加深入的理解。比如紅色代碼塊可以用批處理模式:addbatch方法。代碼中的Thread.sleep()顯得有點多余,主要原因是excel中德數(shù)據(jù)太少。
這是數(shù)據(jù)庫中數(shù)據(jù)的顯示。 以下是原數(shù)據(jù):
最近公司安排的事情做得有點吃力,所以寫點代碼調(diào)節(jié)一下枯燥的心情。
posted on 2014-01-02 09:04 順其自然EVO 閱讀(273) 評論(0) 編輯 收藏 所屬分類: 數(shù)據(jù)庫