1  import java.sql.Connection;
  2  import java.sql.ResultSet;
  3  import java.sql.ResultSetMetaData;
  4  import java.sql.Statement;
  5  import java.sql.SQLException;
  6  import java.io.File;
  7  import java.io.IOException;
  8  import java.util.Scanner;
  9  
 10  /**
 11     Executes all SQL statements from a file or the console.
 12  */
 13  public class ExecSQL
 14  {
 15     public static void main(String[] args) 
 16           throws SQLException, IOException, ClassNotFoundException
 17     {   
 18        if (args.length == 0)
 19        {   
 20           System.out.println(
 21                 "Usage: java -classpath driver_class_path"
 22                 + File.pathSeparator 
 23                 + ". ExecSQL propertiesFile [SQLcommandFile]");
 24           return;
 25        }
 26  
 27        SimpleDataSource.init(args[0]);
 28        
 29        Scanner in; 
 30        if (args.length > 1) 
 31           in = new Scanner(new File(args[1]));
 32        else
 33           in = new Scanner(System.in);
 34        
 35        Connection conn = SimpleDataSource.getConnection();
 36        try
 37        {
 38           Statement stat = conn.createStatement();      
 39           while (in.hasNextLine())
 40           {
 41              String line = in.nextLine();
 42              try
 43              {
 44                 boolean hasResultSet = stat.execute(line);
 45                 if (hasResultSet)
 46                 {
 47                    ResultSet result = stat.getResultSet();
 48                    showResultSet(result);
 49                    result.close();
 50                 }
 51              }
 52              catch (SQLException ex)
 53              {
 54                 System.out.println(ex);
 55              }
 56           }
 57        }
 58        finally
 59        {      
 60           conn.close();
 61        }
 62     }
 63  
 64     /**
 65        Prints a result set.
 66        @param result the result set
 67     */
 68     public static void showResultSet(ResultSet result) 
 69           throws SQLException
 70     { 
 71        ResultSetMetaData metaData = result.getMetaData();
 72        int columnCount = metaData.getColumnCount();
 73  
 74        for (int i = 1; i <= columnCount; i++)
 75        {  
 76           if (i > 1) System.out.print(", ");
 77           System.out.print(metaData.getColumnLabel(i));
 78        }
 79        System.out.println();
 80  
 81        while (result.next())
 82        {  
 83           for (int i = 1; i <= columnCount; i++)
 84           {  
 85              if (i > 1) System.out.print(", ");
 86              System.out.print(result.getString(i));
 87           }
 88           System.out.println();
 89        }
 90     }
 91  }