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