ExecSQL.java

import java.io.*;
import java.util.*;
import java.sql.*;
 
/**
Execute SQL statements from a file or the command line.  Each SQL
statement in the input must be terminated by a line containing only
the word "go".  To end the program, enter a line containing
only the word "quit".

Reads database connection information from a property file named 
"ExecSQL.properties".  Any database drivers used must 
be on the classpath!
*/
class ExecSQL
{
    public static void main(String args[])
    {   
        String line,commandBuf;
        boolean done,go;

        try {
            Reader reader;
            if (args.length == 0)
                reader = new InputStreamReader(System.in);
            else
                reader = new FileReader(args[0]);

            Connection conn = myGetConnection();
            Statement stat = conn.createStatement();

            BufferedReader in = new BufferedReader(reader);

            commandBuf = "";
            done = false;
            go = false;
            while (!done) {
                if (args.length == 0 && commandBuf.equals(""))
                    System.out.println(
                        "\nEnter command (or 'quit' to exit): ");
                line = in.readLine();
                if (line == null)
                    done = true; // End of file.
                else if (line.trim().toLowerCase().equals("quit")) 
                    done = true; // User requested end.
                else if (line.trim().toLowerCase().equals("go"))
                    go = true;
                else if (!line.trim().equals(""))
                    commandBuf = commandBuf + "\n" + line;
                if (go || (done && !commandBuf.equals(""))) {
                    // Execute the accumulated query.
                    // If it's the end of the file, do this even 
                    // without a 'go', because the user forgot it.
                    System.out.println("\nQuery is: " + commandBuf);
                    try {
                        boolean hasResultSet = 
                            stat.execute(commandBuf);
                        if (hasResultSet) {
                            System.out.println("\nOutput is: ");
                            showResultSet(stat,System.out);
                            }
                        else
                            System.out.println("\nNo output.");
                        }
                    catch (SQLException ex) {
                        // Note the use of nested exceptions!
                        while (ex != null) {  
                            ex.printStackTrace();
                            ex = ex.getNextException();
                            }
                        }
                    commandBuf = "";
                    go = false;
                    }
                }

            in.close();
            stat.close();
            conn.close();
            }
        catch (Exception ex) {
            ex.printStackTrace();
            }
    }

    /**
    Connect to a database specified in the property set in file
    "database.properties".

    @return the database connection
    */
    public static Connection myGetConnection()
        throws SQLException,IOException
    {  
        Properties props = new Properties();
        FileInputStream in = 
            new FileInputStream("ExecSQL.properties");
        props.load(in);
        in.close();

        String drivers = props.getProperty("jdbc.drivers");
        if (drivers != null)
            System.setProperty("jdbc.drivers",drivers);
        String url = props.getProperty("jdbc.url");
        String username = props.getProperty("jdbc.username");
        String password = props.getProperty("jdbc.password");

        return DriverManager.getConnection(url,username,password);
    }

    /**
    Print a result set.
    @param stat the statement whose result set should be printed
    */
    public static void showResultSet(Statement stat,PrintStream out) 
        throws SQLException
    { 
        ResultSet result = stat.getResultSet();
        ResultSetMetaData metaData = result.getMetaData();
        int columnCount = metaData.getColumnCount();

        for (int i=1; i<=columnCount; i++) {  
            if (i > 1)
                out.print(", ");
            out.print(metaData.getColumnLabel(i));
            }
        out.println();

        while (result.next()) {  
            for (int i=1; i<=columnCount; i++) {  
                if (i > 1) 
                    out.print(", ");
                String s = result.getString(i);
                if (result.wasNull())
                    out.print("<NULL>");
                else
                    out.print(s);
                }
            out.println();
            }
        result.close();
    }
}