我一般都是先完成功能,然後将其封裝成塊,再添加到項目中,個人癖好不值得借鑒。項目中關于解析excel資料的方式請參考:http://blog.csdn.net/trsli/article/details/17392943
這是已經成功插入資料化資料庫中資料的記錄,我建立的表為db. 這是在控制台的資料輸入
/**将execl資料導入資料庫
* @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) {
//資料.xls檔案路徑
system.out.println("輸入檔案路徑:");
string filename=new scanner(system.in).nextline();
//擷取需要插入資料庫的資料内容
object[][] contents=new poiutil().getmessage(filename);
//擷取資料庫建立表格的字段名
object[] titles=new poiutil().gettitles(filename);
system.out.println("輸入數表格名:");
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");
//拼接字元串,主要是為了完全實作動态建立資料表格以及後期插入資料
<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資料拼裝完成
sql="insert into "+fname+"("+ziduan+") values ("+ blank+")";
buf.append(" );");
stmt.executeupdate(buf.tostring());
system.out.println("預處理...");
thread.sleep(2000);//用于保證資料庫建表操作完成
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];//擷取一行資料
preparedstatement insert=conn.preparestatement(sql);
for(int j=0;j<content.length;j++){
insert.setstring(j+1, content[j].tostring());//預加載資料
insert.executeupdate();//插入資料
system.out.println("第"+i+"行成功...");
thread.sleep(500);
</span> }
system.out.println("插入資料完成");
} catch (sqlexception e) {
整個代碼很簡單,可以從中提取出需要的方法,用于其它需要的地方,而這就是未來需要做的。個人感覺還有許多需要改進的地方,當然自從開始研究poi以來,我還沒有對其進行更加深入的了解。比如紅色代碼塊可以用批處理模式:addbatch方法。代碼中的thread.sleep()顯得有點多餘,主要原因是excel中德資料太少。
這是資料庫中資料的顯示。 以下是原資料:
最近公司安排的事情做得有點吃力,是以寫點代碼調節一下枯燥的心情。
最新内容請見作者的github頁:http://qaseven.github.io/