/**将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("预处理..."); try { 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+"行成功..."); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } </span> } System.out.println("插入数据完成"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } |