Here you can find the source of executeSqlFile(Connection connection, String sqlPath)
Executes the sql scripts in the given sql file.
Parameter | Description |
---|---|
connection | Connection instance to access the database |
sqlPath | the path of the sql file to execute |
Parameter | Description |
---|---|
SQLException | if exception occurs during database operation |
IOException | if fails to read the sql file |
private static void executeSqlFile(Connection connection, String sqlPath) throws SQLException, IOException
//package com.java2s; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; public class Main { /**/*from www . j a va 2 s .c o m*/ * <p> * Executes the sql scripts in the given sql file. * </p> * * @param connection Connection instance to access the database * @param sqlPath the path of the sql file to execute * * @throws SQLException if exception occurs during database operation * @throws IOException if fails to read the sql file */ private static void executeSqlFile(Connection connection, String sqlPath) throws SQLException, IOException { String[] sqlStatements = loadSqlFile(sqlPath); Statement stmt = null; try { stmt = connection.createStatement(); for (int i = 0; i < sqlStatements.length; i++) { if (sqlStatements[i].trim().length() != 0) { stmt.executeUpdate(sqlStatements[i]); } } } finally { closeStatement(stmt); } } /** * <p> * This method return the sql scripts from the given sql file. * </p> * * @param path the path of the sql file * @return the sql scripts * * @throws IOException if fails to read the sql file */ private static String[] loadSqlFile(String path) throws IOException { StringBuffer sb = new StringBuffer(); BufferedReader reader = new BufferedReader(new FileReader(path)); try { String line = reader.readLine(); while (line != null) { line = line.trim(); if (line.length() != 0 && !line.startsWith("--")) { sb.append(line); } line = reader.readLine(); } return sb.toString().split(";"); } finally { reader.close(); } } /** * <p> * Closes the given PreparedStatement instance. * </p> * * @param state the given Statement instance to close. */ static void closeStatement(Statement state) { try { if (state != null) { state.close(); } } catch (SQLException e) { // Ignore } } }