Comment exécuter.fichier de script sql utilisant JDBC [dupliquer]

possibilité de dupliquer:

Je cours .script sql utilisant MySQL avec JDBC

j'ai un fichier de script SQL qui contient 40-50 instructions SQL. Est-il possible d'exécuter ce fichier de script en utilisant JDBC?

54
demandé sur Community 2009-09-30 15:31:30

7 réponses

ce lien pourrait vous aider: http://pastebin.com/f10584951 .

collé ci-dessous pour la postérité:

/*
 * Slightly modified version of the com.ibatis.common.jdbc.ScriptRunner class
 * from the iBATIS Apache project. Only removed dependency on Resource class
 * and a constructor
 */
/*
 *  Copyright 2004 Clinton Begin
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.sql.*;

/**
 * Tool to run database scripts
 */
public class ScriptRunner {

    private static final String DEFAULT_DELIMITER = ";";

    private Connection connection;

    private boolean stopOnError;
    private boolean autoCommit;

    private PrintWriter logWriter = new PrintWriter(System.out);
    private PrintWriter errorLogWriter = new PrintWriter(System.err);

    private String delimiter = DEFAULT_DELIMITER;
    private boolean fullLineDelimiter = false;

    /**
     * Default constructor
     */
    public ScriptRunner(Connection connection, boolean autoCommit,
            boolean stopOnError) {
        this.connection = connection;
        this.autoCommit = autoCommit;
        this.stopOnError = stopOnError;
    }

    public void setDelimiter(String delimiter, boolean fullLineDelimiter) {
        this.delimiter = delimiter;
        this.fullLineDelimiter = fullLineDelimiter;
    }

    /**
     * Setter for logWriter property
     *
     * @param logWriter
     *            - the new value of the logWriter property
     */
    public void setLogWriter(PrintWriter logWriter) {
        this.logWriter = logWriter;
    }

    /**
     * Setter for errorLogWriter property
     *
     * @param errorLogWriter
     *            - the new value of the errorLogWriter property
     */
    public void setErrorLogWriter(PrintWriter errorLogWriter) {
        this.errorLogWriter = errorLogWriter;
    }

    /**
     * Runs an SQL script (read in using the Reader parameter)
     *
     * @param reader
     *            - the source of the script
     */
    public void runScript(Reader reader) throws IOException, SQLException {
        try {
            boolean originalAutoCommit = connection.getAutoCommit();
            try {
                if (originalAutoCommit != this.autoCommit) {
                    connection.setAutoCommit(this.autoCommit);
                }
                runScript(connection, reader);
            } finally {
                connection.setAutoCommit(originalAutoCommit);
            }
        } catch (IOException e) {
            throw e;
        } catch (SQLException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("Error running script.  Cause: " + e, e);
        }
    }

    /**
     * Runs an SQL script (read in using the Reader parameter) using the
     * connection passed in
     *
     * @param conn
     *            - the connection to use for the script
     * @param reader
     *            - the source of the script
     * @throws SQLException
     *             if any SQL errors occur
     * @throws IOException
     *             if there is an error reading from the Reader
     */
    private void runScript(Connection conn, Reader reader) throws IOException,
            SQLException {
        StringBuffer command = null;
        try {
            LineNumberReader lineReader = new LineNumberReader(reader);
            String line = null;
            while ((line = lineReader.readLine()) != null) {
                if (command == null) {
                    command = new StringBuffer();
                }
                String trimmedLine = line.trim();
                if (trimmedLine.startsWith("--")) {
                    println(trimmedLine);
                } else if (trimmedLine.length() < 1
                        || trimmedLine.startsWith("//")) {
                    // Do nothing
                } else if (trimmedLine.length() < 1
                        || trimmedLine.startsWith("--")) {
                    // Do nothing
                } else if (!fullLineDelimiter
                        && trimmedLine.endsWith(getDelimiter())
                        || fullLineDelimiter
                        && trimmedLine.equals(getDelimiter())) {
                    command.append(line.substring(0, line
                            .lastIndexOf(getDelimiter())));
                    command.append(" ");
                    Statement statement = conn.createStatement();

                    println(command);

                    boolean hasResults = false;
                    if (stopOnError) {
                        hasResults = statement.execute(command.toString());
                    } else {
                        try {
                            statement.execute(command.toString());
                        } catch (SQLException e) {
                            e.fillInStackTrace();
                            printlnError("Error executing: " + command);
                            printlnError(e);
                        }
                    }

                    if (autoCommit && !conn.getAutoCommit()) {
                        conn.commit();
                    }

                    ResultSet rs = statement.getResultSet();
                    if (hasResults && rs != null) {
                        ResultSetMetaData md = rs.getMetaData();
                        int cols = md.getColumnCount();
                        for (int i = 0; i < cols; i++) {
                            String name = md.getColumnLabel(i);
                            print(name + "\t");
                        }
                        println("");
                        while (rs.next()) {
                            for (int i = 0; i < cols; i++) {
                                String value = rs.getString(i);
                                print(value + "\t");
                            }
                            println("");
                        }
                    }

                    command = null;
                    try {
                        statement.close();
                    } catch (Exception e) {
                        // Ignore to workaround a bug in Jakarta DBCP
                    }
                    Thread.yield();
                } else {
                    command.append(line);
                    command.append(" ");
                }
            }
            if (!autoCommit) {
                conn.commit();
            }
        } catch (SQLException e) {
            e.fillInStackTrace();
            printlnError("Error executing: " + command);
            printlnError(e);
            throw e;
        } catch (IOException e) {
            e.fillInStackTrace();
            printlnError("Error executing: " + command);
            printlnError(e);
            throw e;
        } finally {
            conn.rollback();
            flush();
        }
    }

    private String getDelimiter() {
        return delimiter;
    }

    private void print(Object o) {
        if (logWriter != null) {
            System.out.print(o);
        }
    }

    private void println(Object o) {
        if (logWriter != null) {
            logWriter.println(o);
        }
    }

    private void printlnError(Object o) {
        if (errorLogWriter != null) {
            errorLogWriter.println(o);
        }
    }

    private void flush() {
        if (logWriter != null) {
            logWriter.flush();
        }
        if (errorLogWriter != null) {
            errorLogWriter.flush();
        }
    }
}
29
répondu Rakesh Juyal 2010-08-15 14:00:01

j'utilise ce bit de code pour importer des instructions sql créées par mysqldump:

public static void importSQL(Connection conn, InputStream in) throws SQLException
{
    Scanner s = new Scanner(in);
    s.useDelimiter("(;(\r)?\n)|(--\n)");
    Statement st = null;
    try
    {
        st = conn.createStatement();
        while (s.hasNext())
        {
            String line = s.next();
            if (line.startsWith("/*!") && line.endsWith("*/"))
            {
                int i = line.indexOf(' ');
                line = line.substring(i + 1, line.length() - " */".length());
            }

            if (line.trim().length() > 0)
            {
                st.execute(line);
            }
        }
    }
    finally
    {
        if (st != null) st.close();
    }
}
18
répondu Omry Yadan 2009-09-30 13:13:02

une autre option, qui ne supporte pas les commentaires, très utile avec AmaterasERD DDL export pour Apache Derby:

public void executeSqlScript(Connection conn, File inputFile) {

    // Delimiter
    String delimiter = ";";

    // Create scanner
    Scanner scanner;
    try {
        scanner = new Scanner(inputFile).useDelimiter(delimiter);
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
        return;
    }

    // Loop through the SQL file statements 
    Statement currentStatement = null;
    while(scanner.hasNext()) {

        // Get statement 
        String rawStatement = scanner.next() + delimiter;
        try {
            // Execute statement
            currentStatement = conn.createStatement();
            currentStatement.execute(rawStatement);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // Release resources
            if (currentStatement != null) {
                try {
                    currentStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            currentStatement = null;
        }
    }
scanner.close();
}
8
répondu Havok 2015-06-18 17:27:46

il suffit de le lire, puis d'utiliser le prepare statement avec le fichier sql complet.

(si je me souviens bien)

AJOUTER: , Vous pouvez aussi lire et split sur ";" et de l'exécuter dans une boucle. N'oubliez pas les commentaires et ajoutez à nouveau le ";"

5
répondu Martijn Courteaux 2009-09-30 13:26:34

vous devriez pouvoir analyser le fichier SQL en déclarations. Et faire une seule déclaration à chaque fois. Si vous savez que votre fichier se compose de simples insert/update/delete vous pouvez utiliser un point-virgule comme énoncé délimiteur. Dans le cas commun vous avez une tâche pour créer votre SQL-Parser dialecte spécifique.

2
répondu Anders D 2010-08-15 13:56:30

j'ai eu le même problème en essayant d'exécuter un script SQL qui crée une base de données SQL. Googler ici et là j'ai trouvé une classe Java initialement écrite par Clinton Begin qui supporte les commentaires (Voir http://pastebin.com/P14HsYAG ). J'ai légèrement modifié le fichier pour tenir compte des triggers où il faut changer le délimiteur par défaut en quelque chose de différent. J'ai utilisé cette version de ScriptRunner (voir http://pastebin.com/sb4bMbVv ). Depuis un (ouvert source et libre) la classe SQLScriptRunner est une utilité absolument nécessaire, il serait bon d'avoir un peu plus d'entrée des développeurs et espérons que nous aurons bientôt une version plus stable de celui-ci.

2
répondu Pantelis Sopasakis 2011-02-11 12:14:27

vous pouvez lire la ligne de script par ligne avec un BufferedReader et ajouter chaque ligne à un StringBuilder de sorte que le script devient une grande chaîne.

alors vous pouvez créer un objet Statement en utilisant JDBC et appeler statement.execute(stringBuilder.toString()) .

-1
répondu nkr1pt 2010-08-15 14:01:23