BULK在Java中插入少数几个表

时间:2013-07-30 04:38:48

标签: java sql-server-2008 bulkinsert

我将BULK INSERT添加到应用程序中,我的代码是这样的:

public void insertData(String filename, JTextField txt)
{

    File f = new File(txt.getText());
    String path = f.getAbsolutePath();
    String createString = "BULK INSERT dummy_import FROM ' " + path + "\\" +filename+ ".txt' WITH (FIELDTERMINATOR = ',')";
    String createStringdet = "BULK INSERT dummy_import_det FROM  " + path + "\\" +filename+ ".txt WITH (FIELDTERMINATOR = ',')";
    List <DummyImpor> dummyimpor = new ArrayList<DummyImpor>(); 
    List <DummyImporDet> dummyimpordet = new ArrayList<DummyImporDet>();
    int  jml_kemasan = 0;
    float bm = 0;
    try  
       { 
           // Create and execute an SQL statement that returns some data.  
            String SQL = "BULK INSERT dbo.dummy_import FROM ' " + path + "\\" +filename+ ".txt' WITH (FIELDTERMINATOR = ',') UNION BULK INSERT dbo.dummy_import_det FROM ' " + path + "\\" +filename+ ".txt' WITH (FIELDTERMINATOR = ',')";  
            DBConnection connect = new DBConnection();
            PreparedStatement ps = connect.getCon().prepareStatement(SQL);


            for (DummyImpor d: dummyimpor) {

                ps.setString(1, d.getSk_import());
                ps.setString(2, d.getSk_batch());
                ps.setString(3, d.getNo_pib());
ps.setInt(4, d.getJml_kemasan());


                for (DummyImporDet dt: dummyimpordet){

                    ps.setString(5, dt.getSk_import_det());
                    ps.setString(6, dt.getNo_hs());
ps.setFloat(7, dt.getBm_hs());

                }

                ps.addBatch();

            }
            ps.executeBatch(); // insert remaining records
            ps.close();

       }  
       catch(Exception e)  
       { 
            System.out.println(e.getMessage()); 
            System.exit(0);  
       } 
}

当我运行它时,但是当该代码用于导入文本文件/数据时,数据尚未导入。有谁知道解决方案?

1 个答案:

答案 0 :(得分:0)

如果你正在使用MSSQL,这看起来像BCP Utility的工作。将两个数据集插入临时表会快得多,然后选择一个包含所需记录的表格。

http://msdn.microsoft.com/en-us/library/ms162802.aspx