Java SQL Execute executeSqlFile(String filename, Connection connection)

Here you can find the source of executeSqlFile(String filename, Connection connection)

Description

Execute the sql statements in a file.

License

Open Source License

Parameter

Parameter Description
filename the sql file.

Exception

Parameter Description
Exception to JUnit

Declaration

private static void executeSqlFile(String filename,
        Connection connection) throws Exception 

Method Source Code

//package com.java2s;
import java.io.FileReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.Statement;
import java.util.ArrayList;

import java.util.List;

public class Main {
    /**/*from w w  w  . ja va  2 s .com*/
     * Execute the sql statements in a file.
     *
     * @param filename the sql file.
     * @throws Exception to JUnit
     */
    private static void executeSqlFile(String filename,
            Connection connection) throws Exception {
        Reader file = new FileReader(filename);
        char[] buffer = new char[1024];
        int retLength = 0;
        StringBuffer content = new StringBuffer();

        while ((retLength = file.read(buffer)) >= 0) {
            content.append(buffer, 0, retLength);
        }

        file.close();

        List sqls = new ArrayList();
        int lastIndex = 0;

        //parse the sqls
        for (int i = 0; i < content.length(); i++) {
            if (content.charAt(i) == ';') {
                sqls.add(content.substring(lastIndex, i).trim());
                lastIndex = i + 1;
            }
        }
        Statement stmt = null;

        try {
            stmt = connection.createStatement();
            ;
            for (int i = 0; i < sqls.size(); i++) {
                stmt.executeUpdate((String) sqls.get(i));
            }
        } finally {
            stmt.close();
        }
    }
}

Related

  1. executeSQL(Connection session, String sql, Object... params)
  2. executeSqlAutoCommit(Connection connection, String sql)
  3. executeSQLCommand(Connection conn, String sql, byte[] blob)
  4. executeSQLCommandWithResult(Connection conn, String sql)
  5. executeSqlFile(Connection connection, String sqlPath)
  6. executeSqlFromSql(Connection connection, String sql, String name)
  7. executeStatement(Connection con, String sql)
  8. executeStatement(Connection conn, String command)
  9. executeStatement(final String databaseName, final String statement)