8
* This example application demonstrates some of the drivers other features
9
* by implementing a simple psql replacement in Java.
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
20
public psql(String args[]) throws ClassNotFoundException, FileNotFoundException, IOException, SQLException
27
Class.forName("org.postgresql.Driver");
29
// Connect to database
30
System.out.println("Connecting to Database URL = " + url);
31
db = DriverManager.getConnection(url, usr, pwd);
33
dbmd = db.getMetaData();
34
st = db.createStatement();
36
// This prints the backend's version
37
System.out.println("Connected to " + dbmd.getDatabaseProductName() + " " + dbmd.getDatabaseProductVersion());
41
// This provides us the means of reading from stdin
42
StreamTokenizer input = new StreamTokenizer(new InputStreamReader(System.in));
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 ***
51
int tt = 0, lineno = 1;
52
while (tt != StreamTokenizer.TT_EOF && ! done)
54
System.out.print("[" + lineno + "] ");
57
// Here, we trap SQLException so they don't terminate the application
60
if ((tt = input.nextToken()) == StreamTokenizer.TT_WORD)
62
processLine(input.sval);
66
catch (SQLException ex)
68
System.out.println(ex.getMessage());
72
System.out.println("Now closing the connection");
78
* This processes a statement
80
public void processLine(String line) throws SQLException
82
if (line.startsWith("\\"))
84
processSlashCommand(line);
88
boolean type = st.execute(line);
94
// A ResultSet was returned
95
ResultSet rs = st.getResultSet();
100
int count = st.getUpdateCount();
104
// This indicates nothing left
109
// An update count was returned
110
System.out.println("Updated " + st.getUpdateCount() + " rows");
115
type = st.getMoreResults();
120
* This displays a result set.
121
* Note: it closes the result once complete.
123
public void displayResult(ResultSet rs) throws SQLException
125
ResultSetMetaData rsmd = rs.getMetaData();
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"));
135
for (int i = 1;i <= cols;i++)
137
Object o = rs.getObject(i);
139
System.out.print("{null}" + (i < cols ? "\t" : "\n"));
141
System.out.print(o.toString() + (i < cols ? "\t" : "\n"));
145
// finally close the result set
150
* This process / commands (for now just /d)
152
public void processSlashCommand(String line) throws SQLException
154
if (line.startsWith("\\d"))
157
if (line.startsWith("\\d "))
159
// Display details about a table
160
String table = line.substring(3);
161
displayResult(dbmd.getColumns(null, null, table, "%"));
165
String types[] = null;
166
if (line.equals("\\d"))
167
types = allUserTables;
168
else if (line.equals("\\di"))
170
else if (line.equals("\\dt"))
172
else if (line.equals("\\ds"))
173
types = usrSequences;
174
else if (line.equals("\\dS"))
177
throw new SQLException("Unsupported \\d command: " + line);
179
// Display details about all system tables
181
// Note: the first two arguments are ignored. To keep to the spec,
182
// you must put null here
184
displayResult(dbmd.getTables(null, null, "%", types));
187
else if (line.equals("\\q")) // Added by CWJ to permit \q command
190
throw new SQLException("Unsupported \\ command: " + line);
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"};
200
* Display some instructions on how to run the example
202
public static void instructions()
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.");
210
* This little lot starts the test
212
public static void main(String args[])
214
System.out.println("PostgreSQL psql example v6.3 rev 1\n");
219
// This line outputs debug information to stderr. To enable this, simply
220
// add an extra parameter to the command line
222
DriverManager.setLogStream(System.err);
227
psql test = new psql(args);
231
System.err.println("Exception caught.\n" + ex);
232
ex.printStackTrace();