1. 程式人生 > 資料庫 >java實現sql批量插入引數

java實現sql批量插入引數

背景:

 需要更新一些不規範的時間格式,如將某個時間格式化為yy-MM-dd,實際上為 yy-MM-dd hh:mm:ss,並且需要提供回滾指令碼。

例如:規範化時間的指令碼如下:

update test set test_date=substring(account_date,1,10) WHERE test_date>'2017-06-01 00:00:00' AND test_date<'2017-09-07 00:00:00'

這個指令碼是ok,但執行時受到影響的行數如果有幾百條甚至上千條記錄的話,回滾指令碼怎麼寫呢?

模板如下:

update test set test_date= '' where id='';

1.首先,從test表中查出上述的引數:

select id,test_date from test where test_date>'2017-06-01 00:00:00' AND test_date<'2017-09-07 00:00:00'

將結果匯入到文字中,名為為param.txt

2.然後執行以下java程式,打印出可執行的回滾指令碼


    private void insertData() throws IOException{        
        FileReader reader = new FileReader("D:\\document\\load\\data1.txt");
        BufferedReader br = new BufferedReader(reader);    
        String updateSql="update test set test_date= '' where id='';";
        String line = null;
        Integer count=0;
        String[] param=new String[2];
        String regexp = "\'\'";
        while((line = br.readLine()) != null) {
            param=line.split("\\\t");
            String first=updateSql.replaceFirst(regexp,"\'"+param[1]+"\'");
            String second=first.replaceFirst(regexp,"\'"+param[0]+"\'");
            System.out.println(second);
            count++;
        }
        br.close();
        reader.close();
    }

3.如果行數較多,需要列印到檔案中(Console列印的記錄數受限的)

 private void insertData() throws IOException{        
        FileReader reader = new FileReader("D:\\document\\load\\data1.txt");
        BufferedReader br = new BufferedReader(reader);    
        StringBuffer sbf=new StringBuffer();
        String updateSql="update test set test_date= '' where id='';";
        String line = null;
        Integer count=0;
        String[] param=new String[2];
        String regexp = "\'\'";
        while((line = br.readLine()) != null) {
            param=line.split("\\\t");
            String first=updateSql.replaceFirst(regexp,"\'"+param[1]+"\'");
            String second=first.replaceFirst(regexp,"\'"+param[0]+"\'");
            //System.out.println(second);
            sbf.append(second).append("\n");
            count++;
        }
        writeFile("D:\\document\\load\\rollback.sql", sbf);
        br.close();
        reader.close();
    }

    public void writeFile(String fileName,StringBuffer stf) 
              throws IOException {
                BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
                writer.write(stf.toString());                 
                writer.close();
            }