~ubuntu-branches/ubuntu/wily/libpgjava/wily

« back to all changes in this revision

Viewing changes to src/interfaces/jdbc/example/psql.java

  • Committer: Bazaar Package Importer
  • Author(s): Stefan Gybas
  • Date: 2002-02-06 23:43:06 UTC
  • Revision ID: james.westby@ubuntu.com-20020206234306-hsg7suqr8q56qg40
Tags: upstream-7.2
ImportĀ upstreamĀ versionĀ 7.2

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
package example;
 
2
 
 
3
import java.io.*;
 
4
import java.sql.*;
 
5
import java.text.*;
 
6
 
 
7
/*
 
8
 * This example application demonstrates some of the drivers other features
 
9
 * by implementing a simple psql replacement in Java.
 
10
 *
 
11
 */
 
12
 
 
13
public class psql
 
14
{
 
15
        Connection      db;             // The connection to the database
 
16
        Statement       st;             // Our statement to run queries with
 
17
        DatabaseMetaData dbmd;  // This defines the structure of the database
 
18
        boolean done = false;             // Added by CWJ to permit \q command
 
19
 
 
20
        public psql(String args[]) throws ClassNotFoundException, FileNotFoundException, IOException, SQLException
 
21
        {
 
22
                String url = args[0];
 
23
                String usr = args[1];
 
24
                String pwd = args[2];
 
25
 
 
26
                // Load the driver
 
27
                Class.forName("org.postgresql.Driver");
 
28
 
 
29
                // Connect to database
 
30
                System.out.println("Connecting to Database URL = " + url);
 
31
                db = DriverManager.getConnection(url, usr, pwd);
 
32
 
 
33
                dbmd = db.getMetaData();
 
34
                st = db.createStatement();
 
35
 
 
36
                // This prints the backend's version
 
37
                System.out.println("Connected to " + dbmd.getDatabaseProductName() + " " + dbmd.getDatabaseProductVersion());
 
38
 
 
39
                System.out.println();
 
40
 
 
41
                // This provides us the means of reading from stdin
 
42
                StreamTokenizer input = new StreamTokenizer(new InputStreamReader(System.in));
 
43
                input.resetSyntax();
 
44
                input.slashSlashComments(true); // allow // as a comment delimiter
 
45
                input.eolIsSignificant(false);  // treat eol's as spaces
 
46
                input.wordChars(32, 126);
 
47
                input.whitespaceChars(59, 59);
 
48
                // input.quoteChar(39); *** CWJ: messes up literals in query string ***
 
49
 
 
50
                // Now the main loop.
 
51
                int tt = 0, lineno = 1;
 
52
                while (tt != StreamTokenizer.TT_EOF && ! done)
 
53
                {
 
54
                        System.out.print("[" + lineno + "] ");
 
55
                        System.out.flush();
 
56
 
 
57
                        // Here, we trap SQLException so they don't terminate the application
 
58
                        try
 
59
                        {
 
60
                                if ((tt = input.nextToken()) == StreamTokenizer.TT_WORD)
 
61
                                {
 
62
                                        processLine(input.sval);
 
63
                                        lineno++;
 
64
                                }
 
65
                        }
 
66
                        catch (SQLException ex)
 
67
                        {
 
68
                                System.out.println(ex.getMessage());
 
69
                        }
 
70
                }
 
71
 
 
72
                System.out.println("Now closing the connection");
 
73
                st.close();
 
74
                db.close();
 
75
        }
 
76
 
 
77
        /*
 
78
         * This processes a statement
 
79
         */
 
80
        public void processLine(String line) throws SQLException
 
81
        {
 
82
                if (line.startsWith("\\"))
 
83
                {
 
84
                        processSlashCommand(line);
 
85
                        return;
 
86
                }
 
87
 
 
88
                boolean type = st.execute(line);
 
89
                boolean loop = true;
 
90
                while (loop)
 
91
                {
 
92
                        if (type)
 
93
                        {
 
94
                                // A ResultSet was returned
 
95
                                ResultSet rs = st.getResultSet();
 
96
                                displayResult(rs);
 
97
                        }
 
98
                        else
 
99
                        {
 
100
                                int count = st.getUpdateCount();
 
101
 
 
102
                                if (count == -1)
 
103
                                {
 
104
                                        // This indicates nothing left
 
105
                                        loop = false;
 
106
                                }
 
107
                                else
 
108
                                {
 
109
                                        // An update count was returned
 
110
                                        System.out.println("Updated " + st.getUpdateCount() + " rows");
 
111
                                }
 
112
                        }
 
113
 
 
114
                        if (loop)
 
115
                                type = st.getMoreResults();
 
116
                }
 
117
        }
 
118
 
 
119
        /*
 
120
         * This displays a result set.
 
121
         * Note: it closes the result once complete.
 
122
         */
 
123
        public void displayResult(ResultSet rs) throws SQLException
 
124
        {
 
125
                ResultSetMetaData rsmd = rs.getMetaData();
 
126
 
 
127
                // Print the result column names
 
128
                int cols = rsmd.getColumnCount();
 
129
                for (int i = 1;i <= cols;i++)
 
130
                        System.out.print(rsmd.getColumnLabel(i) + (i < cols ? "\t" : "\n"));
 
131
 
 
132
                // now the results
 
133
                while (rs.next())
 
134
                {
 
135
                        for (int i = 1;i <= cols;i++)
 
136
                        {
 
137
                                Object o = rs.getObject(i);
 
138
                                if (rs.wasNull())
 
139
                                        System.out.print("{null}" + (i < cols ? "\t" : "\n"));
 
140
                                else
 
141
                                        System.out.print(o.toString() + (i < cols ? "\t" : "\n"));
 
142
                        }
 
143
                }
 
144
 
 
145
                // finally close the result set
 
146
                rs.close();
 
147
        }
 
148
 
 
149
        /*
 
150
         * This process / commands (for now just /d)
 
151
         */
 
152
        public void processSlashCommand(String line) throws SQLException
 
153
        {
 
154
                if (line.startsWith("\\d"))
 
155
                {
 
156
 
 
157
                        if (line.startsWith("\\d "))
 
158
                        {
 
159
                                // Display details about a table
 
160
                                String table = line.substring(3);
 
161
                                displayResult(dbmd.getColumns(null, null, table, "%"));
 
162
                        }
 
163
                        else
 
164
                        {
 
165
                                String types[] = null;
 
166
                                if (line.equals("\\d"))
 
167
                                        types = allUserTables;
 
168
                                else if (line.equals("\\di"))
 
169
                                        types = usrIndices;
 
170
                                else if (line.equals("\\dt"))
 
171
                                        types = usrTables;
 
172
                                else if (line.equals("\\ds"))
 
173
                                        types = usrSequences;
 
174
                                else if (line.equals("\\dS"))
 
175
                                        types = sysTables;
 
176
                                else
 
177
                                        throw new SQLException("Unsupported \\d command: " + line);
 
178
 
 
179
                                // Display details about all system tables
 
180
                                //
 
181
                                // Note: the first two arguments are ignored. To keep to the spec,
 
182
                                //               you must put null here
 
183
                                //
 
184
                                displayResult(dbmd.getTables(null, null, "%", types));
 
185
                        }
 
186
                }
 
187
                else if (line.equals("\\q")) // Added by CWJ to permit \q command
 
188
                        done = true;
 
189
                else
 
190
                        throw new SQLException("Unsupported \\ command: " + line);
 
191
        }
 
192
 
 
193
        private static final String allUserTables[] = {"TABLE", "INDEX", "SEQUENCE"};
 
194
        private static final String usrIndices[] = {"INDEX"};
 
195
        private static final String usrTables[] = {"TABLE"};
 
196
        private static final String usrSequences[] = {"SEQUENCE"};
 
197
        private static final String sysTables[] = {"SYSTEM TABLE", "SYSTEM INDEX"};
 
198
 
 
199
        /*
 
200
         * Display some instructions on how to run the example
 
201
         */
 
202
        public static void instructions()
 
203
        {
 
204
                System.out.println("\nThis example shows how some of the other JDBC features work within the\ndriver. It does this by implementing a very simple psql equivalent in java.\nNot everything that psql does is implemented.\n");
 
205
                System.out.println("Useage:\n java example.psql jdbc:postgresql:database user password [debug]\n\nThe debug field can be anything. It's presence will enable DriverManager's\ndebug trace. Unless you want to see screens of items, don't put anything in\nhere.");
 
206
                System.exit(1);
 
207
        }
 
208
 
 
209
        /*
 
210
         * This little lot starts the test
 
211
         */
 
212
        public static void main(String args[])
 
213
        {
 
214
                System.out.println("PostgreSQL psql example v6.3 rev 1\n");
 
215
 
 
216
                if (args.length < 3)
 
217
                        instructions();
 
218
 
 
219
                // This line outputs debug information to stderr. To enable this, simply
 
220
                // add an extra parameter to the command line
 
221
                if (args.length > 3)
 
222
                        DriverManager.setLogStream(System.err);
 
223
 
 
224
                // Now run the tests
 
225
                try
 
226
                {
 
227
                        psql test = new psql(args);
 
228
                }
 
229
                catch (Exception ex)
 
230
                {
 
231
                        System.err.println("Exception caught.\n" + ex);
 
232
                        ex.printStackTrace();
 
233
                }
 
234
        }
 
235
}