Java SQL Execute executeSQL(Connection connection, String file)

Here you can find the source of executeSQL(Connection connection, String file)

Description

Executes the SQL statements from file.

License

Open Source License

Parameter

Parameter Description
connection the connection.
file the file.

Exception

Parameter Description
Exception to JUnit.

Declaration

private static void executeSQL(Connection connection, String file)
        throws Exception 

Method Source Code

//package com.java2s;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

import java.sql.Connection;

import java.sql.Statement;

public class Main {
    /**/*from  w  w w.ja v a  2s  .co m*/
     * Executes the SQL statements from file.
     * 
     * @param connection
     *            the connection.
     * @param file
     *            the file.
     * 
     * @throws Exception
     *             to JUnit.
     */
    private static void executeSQL(Connection connection, String file)
            throws Exception {
        String[] values = readFile(file).split(";");

        Statement statement = connection.createStatement();
        try {

            for (int i = 0; i < values.length; i++) {
                String sql = values[i].trim();
                if ((sql.length() != 0) && (!sql.startsWith("#"))) {
                    statement.executeUpdate(sql);
                }
            }
        } finally {
            statement.close();
        }
    }

    /**
     * Reads file to a string.
     * 
     * @param fileName
     *            the name of the file to read.
     * 
     * @return a string represents the content.
     * 
     * @throws IOException
     *             if any IO error occurs.
     */
    private static String readFile(String fileName) throws IOException {
        Reader reader = new FileReader(fileName);

        try {
            StringBuilder sb = new StringBuilder();
            char[] buffer = new char[1024];
            int k = 0;
            while ((k = reader.read(buffer)) != -1) {
                sb.append(buffer, 0, k);
            }
            return sb.toString().replace("\r\n", "\n");
        } finally {
            try {
                reader.close();
            } catch (IOException ioe) {
                // Ignore
            }
        }
    }
}

Related

  1. executeShutDownForHSQL(java.sql.Connection connection)
  2. executeSP(Connection conn, String spName, Object... parameters)
  3. executeSql(Connection conn, String sql)
  4. executeSQL(Connection conn, String sql)
  5. executeSql(Connection conn, String sql)
  6. executeSQL(Connection session, String sql, Object... params)
  7. executeSqlAutoCommit(Connection connection, String sql)
  8. executeSQLCommand(Connection conn, String sql, byte[] blob)
  9. executeSQLCommandWithResult(Connection conn, String sql)