使用java以及jdbc不使用第三方庫執行sql檔案指令碼

來源:互聯網
上載者:User

標籤:sqlhelper   for   dir   fileinput   檔案的   title   pack   資料庫   path   

使用java以及jdbc不使用第三方庫執行sql檔案指令碼2017年02月15日 15:51:45閱讀數:660

使用java執行sql指令碼的方法 
解析sql指令碼,刪除不必要的注釋和空行 
將語句按分號拆開

並將最終的語句放入batch裡面 最後進行執行

package test;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.InputStreamReader;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;import java.util.Arrays;import java.util.List;/* * 使用java以及jdbc執行sql指令碼的工具範例程式碼 */public class SqlHelper {    public  static void main(String[] args){        String path = "檔案地址字串";        String sql = getText(path);        List<String> sqlarr = getSql(sql);        for(int i=0; i<10; i++){            System.out.println(i+":"+sqlarr.get(i));        }        try{        SqlHelper.execute(getConn(),sqlarr);        }catch(Exception e){            e.printStackTrace();        }    }    private static Connection getConn() {        String driver = "com.mysql.jdbc.Driver";        String url = "資料庫連接";        String username = "帳號";        String password = "密碼";        Connection conn = null;        try {            Class.forName(driver); //classLoader,載入對應驅動            conn = (Connection) DriverManager.getConnection(url, username, password);        } catch (ClassNotFoundException e) {            e.printStackTrace();        } catch (SQLException e) {            e.printStackTrace();        }        return conn;    }    public static void execute(Connection conn, List<String> sqlFile) throws Exception {          Statement stmt = null;          stmt = conn.createStatement();          for (String sql : sqlFile) {              sql = sql.trim();            if(sql!=null&&!sql.equals(""))            stmt.addBatch(sql);          }          int[] rows = stmt.executeBatch();          System.out.println("Row count:" + Arrays.toString(rows));          conn.close();    }      /*     * getText方法吧path路徑裡面的檔案按行讀數來放入一個大的String裡面去     * 並在換行的時候加入\r\n     */    public static String getText(String path){        File file = new File(path);        if(!file.exists()||file.isDirectory()){            return null;        }        StringBuilder sb = new StringBuilder();        try{            FileInputStream fis = new FileInputStream(path);            InputStreamReader isr = new InputStreamReader(fis,"UTF-8");            BufferedReader br = new BufferedReader(isr);            String temp = null;            temp = br.readLine();            while(temp!=null){                if(temp.length()>=2){                    String str1 = temp.substring(0, 1);                    String str2 = temp.substring(0, 2);                    if(str1.equals("#")||str2.equals("--")||str2.equals("/*")||str2.equals("//")){                        temp = br.readLine();                        continue;                    }                    sb.append(temp+"\r\n");                }                temp = br.readLine();            }            br.close();        }catch(Exception e){            e.printStackTrace();        }        return sb.toString();    }    /*     * getSqlArray方法     * 從檔案的sql字串中分析出能夠獨立執行的sql語句並返回     */    public static List<String> getSql(String sql){        String s = sql;        s = s.replaceAll("\r\n", "\r");        s = s.replaceAll("\r", "\n");        List<String> ret = new ArrayList<String>();        String[] sqlarry = s.split(";");  //用;把所有的語句都分開成一個個單獨的句子        sqlarry = filter(sqlarry);        ret = Arrays.asList(sqlarry);        return ret;    }    public static String[] filter(String[] ss){        List<String> strs = new ArrayList<String>();        for(String s : ss){            if(s!=null&&!s.equals("")){                strs.add(s);            }        }        String[] result = new String[strs.size()];        for(int i=0; i<strs.size(); i++){            result[i] = strs.get(i).toString();        }        return result;    }}

 

使用java以及jdbc不使用第三方庫執行sql檔案指令碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.