Java執行SQL指令檔到資料庫

來源:互聯網
上載者:User

標籤:span   font   常用   roc   parameter   family   append   reader   proc   

方式一:直接讀取SQL指令檔的內容,然後傳遞到SQL中。

代碼:RunSqlService:

    @Autowired    private RunSqlDao runSqlDao;        /**     * 讀取檔案內容到SQL中執行     * @param sqlPath SQL檔案的路徑:如:D:/TestProject/web/sql/指令碼.Sql     */    public void runSqlByReadFileContent(String sqlPath) throws Exception {        try {                         String sqlStr = readFileByLines(sqlPath);            // System.out.println("獲得的文本:" + sqlStr);            if (sqlStr.length() > 0) {                runSqlDao.runSqlBySqlStr(sqlStr);            }        } catch (Exception e) {            e.printStackTrace();            throw e;        }    }        /**     * 以行為單位讀取檔案,常用於讀面向行的格式檔案     */    private String readFileByLines(String filePath) throws Exception {        StringBuffer str = new StringBuffer();        BufferedReader reader = null;        try {            reader = new BufferedReader(new InputStreamReader(                    new FileInputStream(filePath), "UTF-8"));            String tempString = null;            int line = 1;            // 一次讀入一行,直到讀入null為檔案結束            while ((tempString = reader.readLine()) != null) {                // 顯示行號                // System.out.println("line " + line + ": " + tempString);                str = str.append(" " + tempString);                line++;            }            reader.close();        } catch (IOException e) {            e.printStackTrace();            throw e;        } finally {            if (reader != null) {                try {                    reader.close();                } catch (IOException e1) {                }            }        }        return str.toString();    }

RunSqlDao :

    /**     * @param sqlStr     */    public void runSqlBySqlStr(String sqlStr) {        Map<String,Object> map=new HashMap<String,Object>();        map.put("sqlStr", sqlStr);        sqlSessionTemplate.selectList("runSql.runSqlBySqlStr", map);    }

SQLMap:

<mapper namespace="runSql"><select id="runSqlBySqlStr" parameterType="map"><![CDATA[ ${sqlStr}]]></select></mapper>

這種寫法:只支援資料的變化(新增、修改、刪除),且SQL檔案內容以begin開始,以end結束。無法更新表欄位修改等操作。

方式二;使用ScriptRunner

代碼:RunSqlService:

    /**     * 執行sql指令檔 使用ScriptRunner     * @param sqlPath SQL檔案的路徑:如:D:/TestProject/web/sql/指令碼.Sql     */    public void runSqlByScriptRunner(String sqlPath) throws Exception {        try {            SqlSession sqlSession = sqlSessionFactory.openSession();            Connection conn = sqlSession.getConnection();            ScriptRunner runner = new ScriptRunner(conn);            runner.setEscapeProcessing(false);            runner.setSendFullScript(true);                        runner.runScript(new InputStreamReader(new FileInputStream(sqlPath), "UTF-8"));        } catch (Exception e) {            e.printStackTrace();            throw e;        }    }

這種寫法:只能有一行SQL,即一次執行一個SQL語句,否則就會報錯。

方式三:使用ScriptUtils
代碼:RunSqlService:(以下兩種方式:指令碼.Sql 和RunSqlService 在同一目錄下)

方法(1)

    /**     * 執行sql指令檔 使用Spring工具類     */    public void runSqlBySpringUtils() throws Exception {        try {            SqlSession sqlSession = sqlSessionFactory.openSession();            Connection conn = sqlSession.getConnection();            ClassPathResource rc = new ClassPathResource("指令碼.Sql", RunSqlDao.class);            ScriptUtils.executeSqlScript(conn, rc);        } catch (Exception e) {            e.printStackTrace();            throw e;        }    }

方法(2)

    /**     * 執行sql指令檔 使用Spring工具類     */    public void runSqlBySpringUtils() throws Exception {        try {            SqlSession sqlSession = sqlSessionFactory.openSession();            Connection conn = sqlSession.getConnection();            ClassPathResource rc = new ClassPathResource("指令碼.Sql", RunSqlDao.class);            EncodedResource er = new EncodedResource(rc, "utf-8");            ScriptUtils.executeSqlScript(conn, er);        } catch (Exception e) {            e.printStackTrace();            throw e;        }    }

方法(1),指令碼.Sql檔案必須是ANSI的,否則執行到資料中漢字是亂碼。

方法(2)解決了方法(1)的問題,完美了,喜歡的小夥伴們快拿去享用吧。

 

文章為本人原創,轉載請標明出處。

Java執行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.