Commit 2a9bf5b3 authored by PostgreSQL Daemon's avatar PostgreSQL Daemon

parent 9bd681a5
#-------------------------------------------------------------------------
#
# Makefile for JDBC driver
#
# Copyright (c) 2001, PostgreSQL Global Development Group
#
# $PostgreSQL: pgsql/src/interfaces/jdbc/Makefile,v 1.39 2003/11/29 19:52:09 pgsql Exp $
#
#-------------------------------------------------------------------------
subdir = src/interfaces/jdbc
top_builddir = ../../..
include $(top_builddir)/src/Makefile.global
majorversion:= $(shell echo $(VERSION) | sed 's/^\([0-9][0-9]*\)\..*$$/\1/')
minorversion:= $(shell echo $(VERSION) | sed 's/^[0-9][0-9]*\.\([0-9][0-9]*\).*$$/\1/')
build.properties: $(top_builddir)/src/Makefile.global
@echo "# This file was created by 'make build.properties'." > build.properties
@echo major=$(majorversion) >> build.properties
@echo minor=$(minorversion) >> build.properties
@echo fullversion=$(VERSION) >> build.properties
@echo def_pgport=$(DEF_PGPORT) >> build.properties
@echo enable_debug=$(enable_debug) >> build.properties
all: build.properties
$(ANT) -buildfile $(srcdir)/build.xml all
install: installdirs build.properties
$(ANT) -buildfile $(srcdir)/build.xml install \
-Dinstall.directory=$(javadir)
installdirs:
$(mkinstalldirs) $(javadir)
uninstall:
$(ANT) -buildfile $(srcdir)/build.xml uninstall \
-Dinstall.directory=$(javadir)
clean distclean maintainer-clean:
$(ANT) -buildfile $(srcdir)/build.xml clean_all
check: build.properties
$(ANT) -buildfile $(srcdir)/build.xml test
This is a simple readme describing how to compile and use the jdbc driver.
---------------------------------------------------------------------------
This isn't a guide on how to use JDBC - for that refer to sun's web site:
http://java.sun.com/
For problems with this driver, then refer to the postgres-jdbc email
list:
http://www.postgresql.org/
The Driver's home page is:
http://jdbc.postgresql.org/
---------------------------------------------------------------------------
COMPILING
To compile you will need to have ANT installed. To obtain ant go to
http://jakarta.apache.org/ant/index.html and download the binary. Being pure
java it will run on virtually all java platforms. If you have any problems
please email the jdbc list.
Once you have ANT, run the configure script in the top-level directory with
the --with-java option. Then proceed with 'make' and 'make install' as
usual. This will compile the correct driver for your JVM, and build a .jar
file (Java ARchive) called postgresql.jar. The file will be installed in
the directory PREFIX/share/java.
That jar file will contain the driver for _your_ version of the JDK.
If you would like to use ANT directly, first invoke 'make build.properties'
after running the configure script with the java option. This will create a
needed Java properties file from the configured information.
REMEMBER: Once you have compiled the driver, it will work on ALL platforms
that support that version of the API. You don't need to build it for each
platform.
Possible problems
You may see a message similar to:
postgresql/Driver.java:87: interface java.sql.Connection is an interface. It can't be instantiated.
return new Connection (host(), port(), props, database(), url, this);
This is caused by not having the current directory in your CLASSPATH. Under
Linux/Solaris, unset the CLASSPATH environment variable, and rerun ant.
If you are still having problems, prebuilt versions of the driver
are available at http://jdbc.postgresql.org/
---------------------------------------------------------------------------
INSTALLING THE DRIVER
To install the driver, the .class files have to be in the classpath.
ie: under LINUX/SOLARIS (the example here is my linux box):
export CLASSPATH=.:/usr/local/pgsql/share/java/postgresql.jar
---------------------------------------------------------------------------
USING THE DRIVER
To use the driver, you must introduce it to JDBC. Again, there's two ways
of doing this:
1: Hardcoded.
This method hardcodes your driver into your application/applet. You
introduce the driver using the following snippet of code:
try {
Class.forName("org.postgresql.Driver");
} catch(Exception e) {
// your error handling code goes here
}
Remember, this method restricts your code to just the postgresql database.
However, this is how most people load the driver.
2: Parameters
This method specifies the driver from the command line. When running the
application, you specify the driver using the option:
-Djdbc.drivers=org.postgresql.Driver
eg: This is an example of running one of my other projects with the driver:
java -Djdbc.drivers=org.postgresql.Driver uk.org.retep.finder.Main
note: This method only works with Applications (not for Applets).
However, the application is not tied to one driver, so if you needed
to switch databases (why I don't know ;-) ), you don't need to
recompile the application (as long as you havent hardcoded the url's).
---------------------------------------------------------------------------
JDBC URL syntax
The driver recognises JDBC URL's of the form:
jdbc:postgresql:database
jdbc:postgresql://host/database
jdbc:postgresql://host:port/database
Also, you can supply both username and passwords as arguments, by appending
them to the URL. eg:
jdbc:postgresql:database?user=me
jdbc:postgresql:database?user=me&password=mypass
Notes:
1) If you are connecting to localhost or 127.0.0.1 you can leave it out of the
URL. ie: jdbc:postgresql://localhost/mydb can be replaced with
jdbc:postgresql:mydb
2) The port defaults to 5432 if it's left out.
---------------------------------------------------------------------------
That's the basics related to this driver. You'll need to read the JDBC Docs
on how to use it. However, there are some examples included in the example
directory. To build, type: make examples
To run them, they follow the same syntax. For example, the basic example shows
how to insert data, and perform queries:
java example.basic jdbc:postgresql:test user password
---------------------------------------------------------------------------
POSTGRESQL SPECIFICS
--------------------
Large Objects:
A "feature" of PostgreSQL is that access to LargeObjects is only permitted
within a Transaction. Because of this, any use of LargeObjects (also known
as Blobs) requires that the Connection.setAutoCommit() method be called
disabling the autocommit feature.
For example:
Connection db; // open the connection here
db.setAutoCommit(false); // Turn off AutoCommit
------------------
Large Object API
The first thing you need to do is to open the LargeObjectManager. This class
handles the opening of existing objects, and creating new ones. To do this,
you use the following line of code:
LargeObjectManager lobj;
lobj = ((org.postgresql.Connection)db).getLargeObjectAPI();
where db is a reference to an open Connection object.
Once that is done, you can use the API for the lifetime of that Connection.
To create an object, you call the create() method. This takes an argument
with the file modes you intend to use. The following line is normally
sufficient:
int oid = lobj.create(LargeObjectManager.READ|LargeObjectManager.WRITE);
Here, lobj is the LargeObjectManager we have opened earlier, and oid is the
Large Object's oid in the database.
To open an existing object, you use the open() method. This takes an oid, and
the file permissions. It then returns a LargeObject object.
LargeObject obj = lobj.open(oid,LargeObjectManager.WRITE);
Once the LargeObject is open, you can call methods to read, write, seek etc.
Here's the supported methods:
int oid = obj.getOID(); Return the objects oid
obj.close(); Close the object
byte data[] = obj.read(int len); Read len bytes
onj.read(byte data[],int off,int len); Read into data[off] len bytes
obj.write(byte data[]); Write the array data
obj.write(byte data[],int off,int len); Write len bytes from data[off]
obj.seek(int pos,int ref); As fseek in C.
obj.seek(int pos); Move to pos (from the begining)
int pos = obj.tell(); Returns the current position
int size = obj.size(); Returns the objects size
Caveat: If you commit(), rollback() a transaction, or turn on autocommit whilst
an object is open PostgreSQL will close it. You will need to reopen the object
before using it again. Using the existing LargeObject will cause an
SQLException to be thrown.
------------------
JDBC supports database specific data types using the getObject() call. The
following types have their own Java equivalents supplied by the driver:
box, circle, line, lseg, path, point, polygon
When using the getObject() method on a resultset, it returns a PG_Object,
which holds the postgres type, and its value. This object also supports
methods to retrive these types.
Eg: column 3 contains a point, and rs is the ResultSet:
PG_Object o = (PG_Object)rs.getObject(3);
PGpoint p = o.getPoint();
System.out.println("point returned x="+p.x+", y="+p.y);
Also, when using these classes, their toString() methods return the correct
syntax for writing these to the database.
---------------------------------------------------------------------------
This diff is collapsed.
This diff is collapsed.
package example;
import java.sql.*;
import java.util.*;
/*
* Test inserting and extracting Unicode-encoded strings.
*
* Synopsis:
* example.Unicode <url> <user> <password>
* where <url> must specify an existing database to which <user> and
* <password> give access and which has UNICODE as its encoding.
* (To create a database with UNICODE encoding, you need to run createdb
* with the flag "-E UNICODE".)
*
* This test only produces output on error.
*
* @author William Webber <william@live.com.au>
*/
public class Unicode
{
/*
* The url for the database to connect to.
*/
private String url;
/*
* The user to connect as.
*/
private String user;
/*
* The password to connect with.
*/
private String password;
private static void usage()
{
log("usage: example.Unicode <url> <user> <password>");
}
private static void log(String message)
{
System.err.println(message);
}
private static void log(String message, Exception e)
{
System.err.println(message);
e.printStackTrace();
}
public Unicode(String url, String user, String password)
{
this.url = url;
this.user = user;
this.password = password;
}
/*
* Establish and return a connection to the database.
*/
private Connection getConnection() throws SQLException,
ClassNotFoundException
{
Class.forName("org.postgresql.Driver");
Properties info = new Properties();
info.put("user", user);
info.put("password", password);
info.put("charSet", "utf-8");
return DriverManager.getConnection(url, info);
}
/*
* Get string representing a block of 256 consecutive unicode characters.
* We exclude the null character, "'", and "\".
*/
private String getSqlSafeUnicodeBlock(int blockNum)
{
if (blockNum < 0 || blockNum > 255)
throw new IllegalArgumentException("blockNum must be from 0 to "
+ "255: " + blockNum);
StringBuffer sb = new StringBuffer(256);
int blockFirst = blockNum * 256;
int blockLast = blockFirst + 256;
for (int i = blockFirst; i < blockLast; i++)
{
char c = (char) i;
if (c == '\0' || c == '\'' || c == '\\')
continue;
sb.append(c);
}
return sb.toString();
}
/*
* Is the block a block of valid unicode values.
* d800 to db7f is the "unassigned high surrogate" range.
* db80 to dbff is the "private use" range.
* These should not be used in actual Unicode strings;
* at least, jdk1.2 will not convert them to utf-8.
*/
private boolean isValidUnicodeBlock(int blockNum)
{
if (blockNum >= 0xd8 && blockNum <= 0xdb)
return false;
else
return true;
}
/*
* Report incorrect block retrieval.
*/
private void reportRetrievalError(int blockNum, String block,
String retrieved)
{
String message = "Block " + blockNum + " returned incorrectly: ";
int i = 0;
for (i = 0; i < block.length(); i++)
{
if (i >= retrieved.length())
{
message += "too short";
break;
}
else if (retrieved.charAt(i) != block.charAt(i))
{
message +=
"first changed character at position " + i + ", sent as 0x"
+ Integer.toHexString((int) block.charAt(i))
+ ", retrieved as 0x"
+ Integer.toHexString ((int) retrieved.charAt(i));
break;
}
}
if (i >= block.length())
message += "too long";
log(message);
}
/*
* Do the testing.
*/
public void runTest()
{
Connection connection = null;
Statement statement = null;
int blockNum = 0;
final int CREATE = 0;
final int INSERT = 1;
final int SELECT = 2;
final int LIKE = 3;
int mode = CREATE;
try
{
connection = getConnection();
statement = connection.createStatement();
statement.executeUpdate("CREATE TABLE test_unicode "
+ "( blockNum INT PRIMARY KEY, "
+ "block TEXT );");
mode = INSERT;
for (blockNum = 0; blockNum < 256; blockNum++)
{
if (isValidUnicodeBlock(blockNum))
{
String block = getSqlSafeUnicodeBlock(blockNum);
statement.executeUpdate
("INSERT INTO test_unicode VALUES ( " + blockNum
+ ", '" + block + "');");
}
}
mode = SELECT;
for (blockNum = 0; blockNum < 256; blockNum++)
{
if (isValidUnicodeBlock(blockNum))
{
String block = getSqlSafeUnicodeBlock(blockNum);
ResultSet rs = statement.executeQuery
("SELECT block FROM test_unicode WHERE blockNum = "
+ blockNum + ";");
if (!rs.next())
log("Could not retrieve block " + blockNum);
else
{
String retrieved = rs.getString(1);
if (!retrieved.equals(block))
{
reportRetrievalError(blockNum, block, retrieved);
}
}
}
}
mode = LIKE;
for (blockNum = 0; blockNum < 256; blockNum++)
{
if (isValidUnicodeBlock(blockNum))
{
String block = getSqlSafeUnicodeBlock(blockNum);
String likeString = "%" +
block.substring(2, block.length() - 3) + "%" ;
ResultSet rs = statement.executeQuery
("SELECT blockNum FROM test_unicode WHERE block LIKE '"
+ likeString + "';");
if (!rs.next())
log("Could get block " + blockNum + " using LIKE");
}
}
}
catch (SQLException sqle)
{
switch (mode)
{
case CREATE:
log("Exception creating database", sqle);
break;
case INSERT:
log("Exception inserting block " + blockNum, sqle);
break;
case SELECT:
log("Exception selecting block " + blockNum, sqle);
break;
case LIKE:
log("Exception doing LIKE on block " + blockNum, sqle);
break;
default:
log("Exception", sqle);
break;
}
}
catch (ClassNotFoundException cnfe)
{
log("Unable to load driver", cnfe);
return ;
}
try
{
if (statement != null)
statement.close();
if (connection != null)
connection.close();
}
catch (SQLException sqle)
{
log("Exception closing connections", sqle);
}
if (mode > CREATE)
{
// If the backend gets what it regards as garbage on a connection,
// that connection may become unusable. To be safe, we create
// a fresh connection to delete the table.
try
{
connection = getConnection();
statement = connection.createStatement();
statement.executeUpdate("DROP TABLE test_unicode;");
}
catch (Exception sqle)
{
log("*** ERROR: unable to delete test table "
+ "test_unicode; must be deleted manually", sqle);
}
}
}
public static void main(String [] args)
{
if (args.length != 3)
{
usage();
System.exit(1);
}
new Unicode(args[0], args[1], args[2]).runTest();
}
}
package example;
import java.io.*;
import java.sql.*;
/*
*
* $PostgreSQL: pgsql/src/interfaces/jdbc/example/basic.java,v 1.15 2003/11/29 22:41:19 pgsql Exp $
*
* This example tests the basic components of the JDBC driver, and shows
* how even the simplest of queries can be implemented.
*
* To use this example, you need a database to be in existence. This example
* will create a table called basic.
*
* Note: This will only work with post 7.0 drivers.
*
*/
public class basic
{
Connection db; // The connection to the database
Statement st; // Our statement to run queries with
public basic(String args[]) throws ClassNotFoundException, FileNotFoundException, IOException, SQLException
{
String url = args[0];
String usr = args[1];
String pwd = args[2];
// Load the driver
Class.forName("org.postgresql.Driver");
// Connect to database
System.out.println("Connecting to Database URL = " + url);
db = DriverManager.getConnection(url, usr, pwd);
System.out.println("Connected...Now creating a statement");
st = db.createStatement();
// Clean up the database (in case we failed earlier) then initialise
cleanup();
// Now run tests using JDBC methods
doexample();
// Clean up the database
cleanup();
// Finally close the database
System.out.println("Now closing the connection");
st.close();
db.close();
//throw postgresql.Driver.notImplemented();
}
/*
* This drops the table (if it existed). No errors are reported.
*/
public void cleanup()
{
try
{
st.executeUpdate("drop table basic");
}
catch (Exception ex)
{
// We ignore any errors here
}
}
/*
* This performs the example
*/
public void doexample() throws SQLException
{
System.out.println("\nRunning tests:");
// First we need a table to store data in
st.executeUpdate("create table basic (a int2, b int2)");
// Now insert some data, using the Statement
st.executeUpdate("insert into basic values (1,1)");
st.executeUpdate("insert into basic values (2,1)");
st.executeUpdate("insert into basic values (3,1)");
// This shows how to get the oid of a just inserted row
st.executeUpdate("insert into basic values (4,1)");
long insertedOID = ((org.postgresql.PGStatement)st).getLastOID();
System.out.println("Inserted row with oid " + insertedOID);
// Now change the value of b from 1 to 8
st.executeUpdate("update basic set b=8");
System.out.println("Updated " + st.getUpdateCount() + " rows");
// Now delete 2 rows
st.executeUpdate("delete from basic where a<3");
System.out.println("deleted " + st.getUpdateCount() + " rows");
// For large inserts, a PreparedStatement is more efficient, because it
// supports the idea of precompiling the SQL statement, and to store
// directly, a Java object into any column. PostgreSQL doesnt support
// precompiling, but does support setting a column to the value of a
// Java object (like Date, String, etc).
//
// Also, this is the only way of writing dates in a datestyle independent
// manner. (DateStyles are PostgreSQL's way of handling different methods
// of representing dates in the Date data type.)
PreparedStatement ps = db.prepareStatement("insert into basic values (?,?)");
for (int i = 2;i < 5;i++)
{
ps.setInt(1, 4); // "column a" = 5
ps.setInt(2, i); // "column b" = i
ps.executeUpdate(); // executeUpdate because insert returns no data
}
ps.close(); // Always close when we are done with it
// Finally perform a query on the table
System.out.println("performing a query");
ResultSet rs = st.executeQuery("select a, b from basic");
if (rs != null)
{
// Now we run through the result set, printing out the result.
// Note, we must call .next() before attempting to read any results
while (rs.next())
{
int a = rs.getInt("a"); // This shows how to get the value by name
int b = rs.getInt(2); // This shows how to get the value by column
System.out.println(" a=" + a + " b=" + b);
}
rs.close(); // again, you must close the result when done
}
// Now run the query again, showing a more efficient way of getting the
// result if you don't know what column number a value is in
System.out.println("performing another query");
rs = st.executeQuery("select * from basic where b>1");
if (rs != null)
{
// First find out the column numbers.
//
// It's best to do this here, as calling the methods with the column
// numbers actually performs this call each time they are called. This
// really speeds things up on large queries.
//
int col_a = rs.findColumn("a");
int col_b = rs.findColumn("b");
// Now we run through the result set, printing out the result.
// Again, we must call .next() before attempting to read any results
while (rs.next())
{
int a = rs.getInt(col_a); // This shows how to get the value by name
int b = rs.getInt(col_b); // This shows how to get the value by column
System.out.println(" a=" + a + " b=" + b);
}
rs.close(); // again, you must close the result when done
}
// Now test maxrows by setting it to 3 rows
st.setMaxRows(3);
System.out.println("performing a query limited to " + st.getMaxRows());
rs = st.executeQuery("select a, b from basic");
while (rs.next())
{
int a = rs.getInt("a"); // This shows how to get the value by name
int b = rs.getInt(2); // This shows how to get the value by column
System.out.println(" a=" + a + " b=" + b);
}
rs.close(); // again, you must close the result when done
// The last thing to do is to drop the table. This is done in the
// cleanup() method.
}
/*
* Display some instructions on how to run the example
*/
public static void instructions()
{
System.out.println("\nThis example tests the basic components of the JDBC driver, demonstrating\nhow to build simple queries in java.\n");
System.out.println("Useage:\n java example.basic 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.");
System.exit(1);
}
/*
* This little lot starts the test
*/
public static void main(String args[])
{
System.out.println("PostgreSQL basic test v6.3 rev 1\n");
if (args.length < 3)
instructions();
// This line outputs debug information to stderr. To enable this, simply
// add an extra parameter to the command line
if (args.length > 3)
DriverManager.setLogStream(System.err);
// Now run the tests
try
{
basic test = new basic(args);
}
catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex);
ex.printStackTrace();
}
}
}
package example;
import java.io.*;
import java.sql.*;
import org.postgresql.largeobject.*;
/*
* This test attempts to create a blob in the database, then to read
* it back.
*
* Important note: You will notice we import the org.postgresql.largeobject
* package, but don't import the org.postgresql package. The reason for this is
* that importing postgresql can confuse javac (we have conflicting class names
* in org.postgresql.* and java.sql.*). This doesn't cause any problems, as
* long as no code imports org.postgresql.
*
* Under normal circumstances, code using any jdbc driver only needs to import
* java.sql, so this isn't a problem.
*
* It's only if you use the non jdbc facilities, do you have to take this into
* account.
*
*/
public class blobtest
{
Connection db;
Statement s;
LargeObjectManager lobj;
public blobtest(String args[]) throws ClassNotFoundException, FileNotFoundException, IOException, SQLException
{
String url = args[0];
String usr = args[1];
String pwd = args[2];
// Load the driver
Class.forName("org.postgresql.Driver");
// Connect to database
System.out.println("Connecting to Database URL = " + url);
db = DriverManager.getConnection(url, usr, pwd);
// This is required for all LargeObject calls
System.out.println("Connected... First turn off autoCommit()");
db.setAutoCommit(false);
System.out.println("Now creating a statement");
s = db.createStatement();
// Now run tests using postgresql's own Large object api
// NOTE: The methods shown in this example are _NOT_ JDBC, but are
// an implementation of the calls found in libpq. Unless you need to
// use this functionality, look at the jdbc tests on how to access blobs.
ownapi();
// Now run tests using JDBC methods
//jdbcapi(db,s);
// Finally close the database
System.out.println("Now closing the connection");
s.close();
db.close();
}
/*
* Now this is an extension to JDBC, unique to postgresql. Here we fetch
* an PGlobj object, which provides us with access to postgresql's
* large object api.
*/
public void ownapi() throws FileNotFoundException, IOException, SQLException
{
System.out.println("\n----------------------------------------------------------------------\nTesting postgresql large object api\n----------------------------------------------------------------------\n");
// Internally, the driver provides JDBC compliant methods to access large
// objects, however the unique methods available to postgresql makes
// things a little easier.
System.out.println("Gaining access to large object api");
lobj = ((org.postgresql.PGConnection)db).getLargeObjectAPI();
int oid = ownapi_test1();
ownapi_test2(oid);
// Now call the jdbc2api test
jdbc2api(oid);
// finally delete the large object
ownapi_test3(oid);
System.out.println("\n\nOID=" + oid);
}
private int ownapi_test1() throws FileNotFoundException, IOException, SQLException
{
System.out.println("Test 1 Creating a large object\n");
// Ok, test 1 is to create a large object. To do this, we use the create
// method.
System.out.println("Creating a large object");
int oid = lobj.create(LargeObjectManager.READ | LargeObjectManager.WRITE);
DriverManager.println("got large object oid=" + oid);
LargeObject obj = lobj.open(oid, LargeObjectManager.WRITE);
DriverManager.println("got large object obj=" + obj);
// Now open a test file - this class will do
System.out.println("Opening test source object");
FileInputStream fis = new FileInputStream("example/blobtest.java");
// copy the data
System.out.println("Copying file to large object");
byte buf[] = new byte[2048];
int s, tl = 0;
while ((s = fis.read(buf, 0, 2048)) > 0)
{
System.out.println("Block size=" + s + " offset=" + tl);
//System.out.write(buf);
obj.write(buf, 0, s);
tl += s;
}
DriverManager.println("Copied " + tl + " bytes");
// Close the object
System.out.println("Closing object");
obj.close();
return oid;
}
private void ownapi_test2(int oid) throws FileNotFoundException, IOException, SQLException
{
System.out.println("Test 2 Reading a large object and save as a file\n");
// Now open the large object
System.out.println("Opening large object " + oid);
LargeObject obj = lobj.open(oid, LargeObjectManager.READ);
DriverManager.println("got obj=" + obj);
// Now open a test file - this class will do
System.out.println("Opening test destination object");
FileOutputStream fos = new FileOutputStream("blob_testoutput");
// copy the data
System.out.println("Copying large object to file");
byte buf[] = new byte[512];
int s = obj.size();
int tl = 0;
while (s > 0)
{
int rs = buf.length;
if (s < rs)
rs = s;
obj.read(buf, 0, rs);
fos.write(buf, 0, rs);
tl += rs;
s -= rs;
}
DriverManager.println("Copied " + tl + "/" + obj.size() + " bytes");
// Close the object
System.out.println("Closing object");
obj.close();
}
private void ownapi_test3(int oid) throws SQLException
{
System.out.println("Test 3 Deleting a large object\n");
// Now open the large object
System.out.println("Deleting large object " + oid);
lobj.unlink(oid);
}
// This tests the Blob interface of the JDBC 2.0 specification
public void jdbc2api(int oid) throws SQLException, IOException
{
System.out.println("Testing JDBC2 Blob interface:");
jdbc2api_cleanup();
System.out.println("Creating Blob on large object " + oid);
s.executeUpdate("create table basic (a oid)");
System.out.println("Inserting row");
s.executeUpdate("insert into basic values (" + oid + ")");
System.out.println("Selecting row");
ResultSet rs = s.executeQuery("select a from basic");
if (rs != null)
{
while (rs.next())
{
System.out.println("Fetching Blob");
Blob b = rs.getBlob("a");
System.out.println("Blob.length() = " + b.length());
System.out.println("Characters 400-500:");
System.out.write(b.getBytes(400l, 100));
System.out.println();
}
rs.close();
}
System.out.println("Cleaning up");
jdbc2api_cleanup();
}
private void jdbc2api_cleanup() throws SQLException
{
db.setAutoCommit(true);
try
{
s.executeUpdate("drop table basic");
}
catch (Exception ex)
{
// We ignore any errors here
}
db.setAutoCommit(false);
}
public static void instructions()
{
System.err.println("java example.blobtest jdbc-url user password [debug]");
System.err.println("\nExamples:\n");
System.err.println("java -Djdbc.driver=org.postgresql.Driver example.blobtest jdbc:postgresql:test postgres password\nThis will run the tests on the database test on the local host.\n");
System.err.println("java -Djdbc.driver=org.postgresql.Driver example.blobtest jdbc:postgresql:test postgres password debug\nThis is the same as above, but will output debug information.\n");
System.err.println("This example tests the binary large object api of the driver.\nThis allows images or java objects to be stored in the database, and retrieved\nusing both postgresql's own api, and the standard JDBC api.");
}
public static void main(String args[])
{
System.out.println("PostgreSQL blobtest v7.0 rev 1\n");
if (args.length < 3)
{
instructions();
System.exit(1);
}
// This line outputs debug information to stderr. To enable this, simply
// add an extra parameter to the command line
if (args.length > 3)
DriverManager.setLogStream(System.err);
// Now run the tests
try
{
blobtest test = new blobtest(args);
}
catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex);
ex.printStackTrace();
}
}
}
package example.corba;
import java.io.*;
import java.sql.*;
import org.omg.CosNaming.*;
/*
* This class is the frontend to our mini CORBA application.
*
* It has no GUI, just a text frontend to keep it simple.
*
* $PostgreSQL: pgsql/src/interfaces/jdbc/example/corba/StockClient.java,v 1.7 2003/11/29 22:41:21 pgsql Exp $
*/
public class StockClient
{
org.omg.CosNaming.NamingContext nameService;
stock.StockDispenser dispenser;
stock.StockItem item;
BufferedReader in;
public StockClient(String[] args)
{
try
{
// We need this for our IO
in = new BufferedReader(new InputStreamReader(System.in));
// Initialize the orb
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, null);
// Get a reference to the Naming Service
org.omg.CORBA.Object nameServiceObj = orb.resolve_initial_references("NameService");
if (nameServiceObj == null)
{
System.err.println("nameServiceObj == null");
return ;
}
nameService = org.omg.CosNaming.NamingContextHelper.narrow(nameServiceObj);
if (nameService == null)
{
System.err.println("nameService == null");
return ;
}
// Resolve the dispenser
NameComponent[] dispName = {
new NameComponent("StockDispenser", "Stock")
};
dispenser = stock.StockDispenserHelper.narrow(nameService.resolve(dispName));
if (dispenser == null)
{
System.err.println("dispenser == null");
return ;
}
// Now run the front end.
run();
}
catch (Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
System.exit(1);
}
}
public static void main(String[] args)
{
new StockClient(args);
}
public void run()
{
// First reserve a StockItem
try
{
item = dispenser.reserveItem();
}
catch (Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
System.exit(1);
}
mainMenu();
// finally free the StockItem
try
{
dispenser.releaseItem(item);
}
catch (Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
System.exit(1);
}
}
private void mainMenu()
{
boolean run = true;
while (run)
{
System.out.println("\nCORBA Stock System\n");
System.out.println(" 1 Display stock item");
System.out.println(" 2 Remove item from stock");
System.out.println(" 3 Put item into stock");
System.out.println(" 4 Order item");
System.out.println(" 5 Display all items");
System.out.println(" 0 Exit");
int i = getMenu("Main", 5);
switch (i)
{
case 0:
run = false;
break;
case 1:
displayItem();
break;
case 2:
bookOut();
break;
case 3:
bookIn();
break;
case 4:
order(0);
break;
case 5:
displayAll();
break;
}
}
}
private void displayItem()
{
try
{
int id = getMenu("\nStockID to display", item.getLastID());
if (id > 0)
{
item.fetchItem(id);
System.out.println("========================================");
String status = "";
if (!item.isItemValid())
status = " ** Superceded **";
int av = item.getAvailable();
System.out.println(" Stock ID: " + id + status +
"\nItems Available: " + av +
"\nItems on order: " + item.getOrdered() +
"\n Description: " + item.getDescription());
System.out.println("========================================");
if (av > 0)
if (yn("Take this item out of stock?"))
{
int rem = 1;
if (av > 1)
rem = getMenu("How many?", av);
if (rem > 0)
item.removeStock(rem);
}
}
}
catch (Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
}
}
private void bookOut()
{
try
{
int id = getMenu("\nStockID to take out", item.getLastID());
if (id > 0)
{
item.fetchItem(id);
int av = item.getAvailable();
if (av > 0)
if (yn("Take this item out of stock?"))
{
int rem = 1;
if (av > 1)
rem = getMenu("How many?", av);
if (rem > 0)
item.removeStock(rem);
}
else
{
System.out.println("This item is not in stock.");
int order = item.getOrdered();
if (order > 0)
System.out.println("There are " + item.getOrdered() + " items on order.");
else
{
if (item.isItemValid())
{
System.out.println("You will need to order some more " + item.getDescription());
order(id);
}
else
System.out.println("This item is now obsolete");
}
}
}
else
System.out.println(item.getDescription() + "\nThis item is out of stock");
}
catch (Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
}
}
// book an item into stock
private void bookIn()
{
try
{
int id = getMenu("\nStockID to book in", item.getLastID());
item.fetchItem(id);
System.out.println(item.getDescription());
if (item.getOrdered() > 0)
{
int am = getMenu("How many do you want to book in", item.getOrdered());
if (am > 0)
item.addNewStock(am);
}
else
System.out.println("You don't have any of this item on ordered");
}
catch (Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
}
}
// Order an item
private void order(int id)
{
try
{
if (id == 0)
id = getMenu("\nStockID to order", item.getLastID());
item.fetchItem(id);
System.out.println(item.getDescription());
int am = getMenu("How many do you want to order", 999);
if (am > 0)
item.orderStock(am);
}
catch (Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
}
}
private void displayAll()
{
try
{
boolean cont = true;
int nr = item.getLastID();
String header = "\nId\tAvail\tOrdered\tDescription";
System.out.println(header);
for (int i = 1;i <= nr && cont;i++)
{
item.fetchItem(i);
System.out.println("" + i + "\t" + item.getAvailable() + "\t" + item.getOrdered() + "\t" + item.getDescription());
if ((i % 20) == 0)
{
if ((cont = yn("Continue?")))
System.out.println(header);
}
}
}
catch (Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
}
}
private int getMenu(String title, int max)
{
int v = -1;
while (v < 0 || v > max)
{
System.out.print(title);
System.out.print(" [0-" + max + "]: ");
System.out.flush();
try
{
v = Integer.parseInt(in.readLine());
}
catch (Exception nfe)
{
v = -1;
}
}
return v;
}
private boolean yn(String title)
{
try
{
while (true)
{
System.out.print(title);
System.out.flush();
String s = in.readLine();
if (s.startsWith("y") || s.startsWith("Y"))
return true;
if (s.startsWith("n") || s.startsWith("N"))
return false;
}
}
catch (Exception nfe)
{
System.out.println(nfe.toString());
nfe.printStackTrace();
System.exit(1);
}
return false;
}
}
package example.corba;
import java.sql.*;
/*
* This class handles the JDBC side of things. It opens a connection to
* the database, and performes queries on that database.
*
* In essence, you could use this class on it's own. The rest of the classes
* in this example handle either the CORBA mechanism, or the frontend.
*
* Note: Before you ask, why perform a query on each call, you have to remember
* that an object could be changed by another client, and we need to ensure that
* the returned data is live and accurate.
*
* $PostgreSQL: pgsql/src/interfaces/jdbc/example/corba/StockDB.java,v 1.5 2003/11/29 22:41:21 pgsql Exp $
*/
public class StockDB
{
Connection con;
Statement st;
// the current stock number
int id = -1;
public void connect(String url, String usr, String pwd) throws Exception
{
Class.forName("org.postgresql.Driver");
System.out.println("Connecting to " + url);
con = DriverManager.getConnection(url, usr, pwd);
st = con.createStatement();
}
public void closeConnection() throws Exception
{
con.close();
}
public void fetchItem(int id) throws Exception
{
this.id = id;
}
public int newItem() throws Exception
{
// tba
return -1;
}
public String getDescription() throws SQLException
{
ResultSet rs = st.executeQuery("select description from stock where id=" + id);
if (rs != null)
{
rs.next();
String s = rs.getString(1);
rs.close();
return s;
}
throw new SQLException("No ResultSet");
}
public int getAvailable() throws SQLException
{
ResultSet rs = st.executeQuery("select avail from stock where id=" + id);
if (rs != null)
{
rs.next();
int v = rs.getInt(1);
rs.close();
return v;
}
throw new SQLException("No ResultSet");
}
public int getOrdered() throws SQLException
{
ResultSet rs = st.executeQuery("select ordered from stock where id=" + id);
if (rs != null)
{
rs.next();
int v = rs.getInt(1);
rs.close();
return v;
}
throw new SQLException("No ResultSet");
}
public boolean isItemValid() throws SQLException
{
ResultSet rs = st.executeQuery("select valid from stock where id=" + id);
if (rs != null)
{
rs.next();
boolean b = rs.getBoolean(1);
rs.close();
return b;
}
throw new SQLException("No ResultSet");
}
public void addNewStock(int amount) throws SQLException
{
st.executeUpdate("update stock set avail=avail+" + amount +
", ordered=ordered-" + amount +
" where id=" + id + " and ordered>=" + amount);
}
public void removeStock(int amount) throws SQLException
{
st.executeUpdate("update stock set avail=avail-" + amount +
" where id=" + id);
}
public void orderStock(int amount) throws SQLException
{
st.executeUpdate("update stock set ordered=ordered+" + amount +
" where id=" + id);
}
public int getLastID() throws SQLException
{
ResultSet rs = st.executeQuery("select max(id) from stock");
if (rs != null)
{
rs.next();
int v = rs.getInt(1);
rs.close();
return v;
}
throw new SQLException("No ResultSet");
}
}
package example.corba;
import org.omg.CosNaming.*;
/*
* This class implements the server side of the example.
*
* $PostgreSQL: pgsql/src/interfaces/jdbc/example/corba/StockDispenserImpl.java,v 1.6 2003/11/29 22:41:21 pgsql Exp $
*/
public class StockDispenserImpl extends stock._StockDispenserImplBase
{
private int maxObjects = 10;
private int numObjects = 0;
private StockItemStatus[] stock = new StockItemStatus[maxObjects];
public StockDispenserImpl(String[] args, String name, int num)
{
super();
try
{
// get reference to orb
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, null);
// prestart num objects
if (num >= maxObjects)
num = maxObjects;
numObjects = num;
for (int i = 0;i < numObjects;i++)
{
stock[i] = new StockItemStatus();
stock[i].ref = new StockItemImpl(args, "StockItem" + (i + 1));
orb.connect(stock[i].ref);
}
}
catch (org.omg.CORBA.SystemException e)
{
e.printStackTrace();
}
}
/*
* This method, defined in stock.idl, reserves a slot in the dispenser
*/
public stock.StockItem reserveItem() throws stock.StockException
{
for (int i = 0;i < numObjects;i++)
{
if (!stock[i].inUse)
{
stock[i].inUse = true;
System.out.println("Reserving slot " + i);
return stock[i].ref;
}
}
return null;
}
/*
* This releases a slot from the dispenser
*/
public void releaseItem(stock.StockItem item) throws stock.StockException
{
for (int i = 0;i < numObjects;i++)
{
if (stock[i].ref.getInstanceName().equals(item.getInstanceName()))
{
stock[i].inUse = false;
System.out.println("Releasing slot " + i);
return ;
}
}
System.out.println("Reserved object not a member of this dispenser");
return ;
}
/*
* This class defines a slot in the dispenser
*/
class StockItemStatus
{
StockItemImpl ref;
boolean inUse;
StockItemStatus()
{
ref = null;
inUse = false;
}
}
}
package example.corba;
import org.omg.CosNaming.*;
/*
* This class implements the server side of the example.
*
* $PostgreSQL: pgsql/src/interfaces/jdbc/example/corba/StockItemImpl.java,v 1.4 2003/11/29 22:41:21 pgsql Exp $
*/
public class StockItemImpl extends stock._StockItemImplBase
{
private StockDB db;
private String instanceName;
public StockItemImpl(String[] args, String iname)
{
super();
try
{
db = new StockDB();
db.connect(args[1], args[2], args[3]);
System.out.println("StockDB object " + iname + " created");
instanceName = iname;
}
catch (Exception e)
{
e.printStackTrace();
}
}
/*
* This is defined in stock.idl
*
* It sets the item to view
*/
public void fetchItem(int id) throws stock.StockException
{
try
{
db.fetchItem(id);
}
catch (Exception e)
{
throw new stock.StockException(e.toString());
}
}
/*
* This is defined in stock.idl
*
* It sets the item to view
*/
public int newItem() throws stock.StockException
{
try
{
return db.newItem();
}
catch (Exception e)
{
throw new stock.StockException(e.toString());
}
}
/*
* This is defined in stock.idl
*
* It returns the description of a Stock item
*/
public String getDescription() throws stock.StockException
{
try
{
return db.getDescription();
}
catch (Exception e)
{
throw new stock.StockException(e.toString());
}
}
/*
* This is defined in stock.idl
*
* It returns the description of a Stock item
*/
public int getAvailable() throws stock.StockException
{
try
{
return db.getAvailable();
}
catch (Exception e)
{
throw new stock.StockException(e.toString());
}
}
/*
* This is defined in stock.idl
*
* It returns the description of a Stock item
*/
public int getOrdered() throws stock.StockException
{
try
{
return db.getOrdered();
}
catch (Exception e)
{
throw new stock.StockException(e.toString());
}
}
/*
* This is defined in stock.idl
*
* It returns the description of a Stock item
*/
public boolean isItemValid() throws stock.StockException
{
try
{
return db.isItemValid();
}
catch (Exception e)
{
throw new stock.StockException(e.toString());
}
}
/*
* This is defined in stock.idl
*
* It returns the description of a Stock item
*/
public void addNewStock(int id) throws stock.StockException
{
try
{
db.addNewStock(id);
}
catch (Exception e)
{
throw new stock.StockException(e.toString());
}
}
/*
* This is defined in stock.idl
*
* It returns the description of a Stock item
*/
public void removeStock(int id) throws stock.StockException
{
try
{
db.removeStock(id);
}
catch (Exception e)
{
throw new stock.StockException(e.toString());
}
}
/*
* This is defined in stock.idl
*
* It returns the description of a Stock item
*/
public void orderStock(int id) throws stock.StockException
{
try
{
db.orderStock(id);
}
catch (Exception e)
{
throw new stock.StockException(e.toString());
}
}
/*
* This returns the highest id used, hence the number of items available
*/
public int getLastID() throws stock.StockException
{
try
{
return db.getLastID();
}
catch (Exception e)
{
throw new stock.StockException(e.toString());
}
}
/*
* This is used by our Dispenser
*/
public String getInstanceName()
{
return instanceName;
}
}
package example.corba;
import org.omg.CosNaming.*;
/*
* This class implements the server side of the example.
*
* $PostgreSQL: pgsql/src/interfaces/jdbc/example/corba/StockServer.java,v 1.6 2003/11/29 22:41:21 pgsql Exp $
*/
public class StockServer
{
public static void main(String[] args)
{
int numInstances = 3;
try
{
// Initialise the ORB
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, null);
// Create the StockDispenser object
StockDispenserImpl dispenser = new StockDispenserImpl(args, "Stock Dispenser", numInstances);
// Export the new object
orb.connect(dispenser);
// Get the naming service
org.omg.CORBA.Object nameServiceObj = orb.resolve_initial_references("NameService");
if (nameServiceObj == null)
{
System.err.println("nameServiceObj = null");
return ;
}
org.omg.CosNaming.NamingContext nameService = org.omg.CosNaming.NamingContextHelper.narrow(nameServiceObj);
if (nameService == null)
{
System.err.println("nameService = null");
return ;
}
// bind the dispenser into the naming service
NameComponent[] dispenserName = {
new NameComponent("StockDispenser", "Stock")
};
nameService.rebind(dispenserName, dispenser);
// Now wait forever for the current thread to die
Thread.currentThread().join();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
The CORBA example is the most complicated of the examples. It
aims to show how to use JDBC & Java2's ORB to access PostgreSQL.
To compile:
Type "make corba" to build the example. This will create a new directory
stock which contains the stubs needed by the orb, and all required classes
under the example/corba directory.
To run:
NOTE: To run, you will need 3 shells on Win32 (under unix you can get away
with two shells):
1: Start the naming service
Unix: tnameserv -ORBInitialPort 1050 &
Win32: tnameserv -ORBInitialPort 1050
2: Start the StockServer
java example.corba.StockServer 3 jdbc:postgresql:dbase user passwd -ORBInitialPort 1050
Where:
3 Number of concurrent sessions to allow
dbase The database (including a hostname if required)
user The PostgreSQL user name
passwd The password
3: Using a fresh shell, run the client:
java example.corba.StockClient -ORBInitialPort 1050
// $PostgreSQL: pgsql/src/interfaces/jdbc/example/corba/stock.idl,v 1.2 2003/11/29 22:41:21 pgsql Exp $
//
// This is our CORBA bindings for a very simple stock control
// system.
//
// $PostgreSQL: pgsql/src/interfaces/jdbc/example/corba/stock.idl,v 1.2 2003/11/29 22:41:21 pgsql Exp $
//
// For some reason, idltojava on my setup doesn't like this to be
// in caps. It could be a problem with Win95 & Samba, but for now,
// this is in lowercase
module stock
{
exception StockException
{
string reason;
};
interface StockItem
{
void fetchItem(in long id) raises (StockException);
long newItem() raises (StockException);
string getDescription() raises (StockException);
long getAvailable() raises (StockException);
long getOrdered() raises (StockException);
boolean isItemValid() raises (StockException);
void addNewStock(in long amount) raises (StockException);
void removeStock(in long amount) raises (StockException);
void orderStock(in long amount) raises (StockException);
long getLastID() raises (StockException);
string getInstanceName();
};
interface StockDispenser
{
StockItem reserveItem() raises (StockException);
void releaseItem(in StockItem item) raises (StockException);
};
};
--
-- This creates the database for the stock example
-- $PostgreSQL: pgsql/src/interfaces/jdbc/example/corba/stock.sql,v 1.2 2003/11/29 22:41:21 pgsql Exp $
--
drop table stock;
create table stock (
id int4,
avail int4,
ordered int4,
valid bool,
description text
);
create index stock_id on stock(id);
copy stock from stdin;
1 19 0 t Dell Latitude XPi P133 Laptop
2 3 2 t Iomega Zip Plus drive
3 2 0 f Iomega Ext/Par drive
4 0 4 t Iomega Ext USB drive
5 200 0 t Blank Unbranded CDR media
6 20 30 t Iomega Zip media 100Mb
\.
grant all on stock to public;
grant all on stock_id to public;
package example;
import java.io.*;
import java.sql.*;
/*
* This example tests the various date styles that are available to postgresql.
*
* To use this example, you need a database to be in existence. This example
* will create a table called datestyle.
*/
public class datestyle
{
Connection db; // The connection to the database
Statement st; // Our statement to run queries with
// This is our standard to compare results with.
java.sql.Date standard;
// This is a list of the available date styles including variants.
// These have to match what the "set datestyle" statement accepts.
String styles[] = {
"postgres,european",
"postgres,us",
"iso", // iso has no variants - us/european has no affect
"sql,european",
"sql,us",
"german" // german has no variants - us/european has no affect
};
public datestyle(String args[]) throws ClassNotFoundException, FileNotFoundException, IOException, SQLException
{
String url = args[0];
String usr = args[1];
String pwd = args[2];
// Load the driver
Class.forName("org.postgresql.Driver");
// Connect to database
System.out.println("Connecting to Database URL = " + url);
db = DriverManager.getConnection(url, usr, pwd);
System.out.println("Connected...Now creating a statement");
st = db.createStatement();
// Clean up the database (in case we failed earlier) then initialise
cleanup();
init();
// Now run tests using JDBC methods
doexample();
// Clean up the database
cleanup();
// Finally close the database
System.out.println("Now closing the connection");
st.close();
db.close();
}
/*
* This drops the table (if it existed). No errors are reported.
*/
public void cleanup()
{
try
{
st.executeUpdate("drop table datestyle");
}
catch (Exception ex)
{
// We ignore any errors here
}
}
/*
* This initialises the database for this example
*/
public void init() throws SQLException
{
// Create a table holding a single date
st.executeUpdate("create table datestyle (dt date)");
// Now create our standard date for the test.
//
// NB: each component of the date should be different, otherwise the tests
// will not be valid.
//
// NB: January = 0 here
//
standard = new java.sql.Date(98, 0, 8);
// Now store the result.
//
// This is an example of how to set a date in a date style independent way.
// The only way of doing this is by using a PreparedStatement.
//
PreparedStatement ps = db.prepareStatement("insert into datestyle values (?)");
ps.setDate(1, standard);
ps.executeUpdate();
ps.close();
}
/*
* This performs the example
*/
public void doexample() throws SQLException
{
System.out.println("\nRunning tests:");
for (int i = 0;i < styles.length;i++)
{
System.out.print("Test " + i + " - " + styles[i]);
System.out.flush();
// set the style
st.executeUpdate("set datestyle='" + styles[i] + "'");
// Now because the driver needs to know what the current style is,
// we have to run the following:
st.executeUpdate("show datestyle");
// This is a limitation, but there is no real way around this.
// Now we query the table.
ResultSet rs = st.executeQuery("select dt from datestyle");
// Throw an exception if there is no result (if the table is empty
// there should still be a result).
if (rs == null)
throw new SQLException("The test query returned no data");
while (rs.next())
{
// The JDBC spec states we should only read each column once.
// In the current implementation of the driver, this is not necessary.
// Here we use this fact to see what the query really returned.
if (standard.equals(rs.getDate(1)))
System.out.println(" passed, returned " + rs.getString(1));
else
System.out.println(" failed, returned " + rs.getString(1));
}
rs.close();
}
}
/*
* Display some instructions on how to run the example
*/
public static void instructions()
{
System.out.println("\nThis example tests the drivers ability to handle dates correctly if the\nbackend is running any of the various date styles that it supports.\nIdealy this should work fine. If it doesn't, then there is something wrong\npossibly in postgresql.Connection or in the backend itself. If this does occur\nthen please email a bug report.\n");
System.out.println("Useage:\n java example.datestyle 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.");
System.exit(1);
}
/*
* This little lot starts the test
*/
public static void main(String args[])
{
System.out.println("PostgreSQL datestyle test v6.3 rev 1\n");
if (args.length < 3)
instructions();
// This line outputs debug information to stderr. To enable this, simply
// add an extra parameter to the command line
if (args.length > 3)
DriverManager.setLogStream(System.err);
// Now run the tests
try
{
datestyle test = new datestyle(args);
}
catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex);
ex.printStackTrace();
}
}
}
package example;
import java.io.*;
import java.sql.*;
/*
* This example application is not really an example. It actually performs
* some tests on various methods in the DatabaseMetaData and ResultSetMetaData
* classes.
*
* To use it, simply have a database created. It will create some work tables
* and run tests on them.
*/
public class metadata
{
Connection db; // The connection to the database
Statement st; // Our statement to run queries with
DatabaseMetaData dbmd; // This defines the structure of the database
/*
* These are the available tests on DatabaseMetaData
*/
public void doDatabaseMetaData() throws SQLException
{
if (doTest("getProcedures() - should show all available procedures"))
displayResult(dbmd.getProcedures(null, null, null));
if (doTest("getProcedures() with pattern - should show all circle procedures"))
displayResult(dbmd.getProcedures(null, null, "circle%"));
if (doTest("getProcedureColumns() on circle procedures"))
displayResult(dbmd.getProcedureColumns(null, null, "circle%", null));
if (doTest("getTables()"))
displayResult(dbmd.getTables(null, null, null, null));
if (doTest("getColumns() - should show all tables, can take a while to run"))
displayResult(dbmd.getColumns(null, null, null, null));
if (doTest("getColumns() - should show the test_b table"))
displayResult(dbmd.getColumns(null, null, "test_b", null));
if (doTest("getColumnPrivileges() - should show all tables"))
displayResult(dbmd.getColumnPrivileges(null, null, null, null));
if (doTest("getPrimaryKeys()"))
displayResult(dbmd.getPrimaryKeys(null, null, null));
if (doTest("getTypeInfo()"))
displayResult(dbmd.getTypeInfo());
}
/*
* These are the available tests on ResultSetMetaData
*/
public void doResultSetMetaData() throws SQLException
{
String sql = "select imagename,descr,source,cost from test_a,test_b,test_c where test_a.id=test_b.imageid and test_a.id=test_c.imageid";
System.out.println("Executing query for tests");
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
if (doTest("isCurrency()"))
System.out.println("isCurrency on col 1 = " + rsmd.isCurrency(1) + " should be false\nisCurrency on col 4 = " + rsmd.isCurrency(4) + " should be true");
// Finally close the query. Now give the user a chance to display the
// ResultSet.
//
// NB: displayResult() actually closes the ResultSet.
if (doTest("Display query result"))
{
System.out.println("Query: " + sql);
displayResult(rs);
}
else
rs.close();
}
/*
* This creates some test data
*/
public void init() throws SQLException
{
System.out.println("Creating some tables");
cleanup();
st.executeUpdate("create table test_a (imagename name,image oid,id int4)");
st.executeUpdate("create table test_b (descr text,imageid int4,id int4)");
st.executeUpdate("create table test_c (source text,cost money,imageid int4)");
System.out.println("Adding some data");
st.executeUpdate("insert into test_a values ('test1',0,1)");
st.executeUpdate("insert into test_b values ('A test description',1,2)");
st.executeUpdate("insert into test_c values ('nowhere particular','$10.99',1)");
}
/*
* This removes the test data
*/
public void cleanup() throws SQLException
{
try
{
st.executeUpdate("drop table test_a");
st.executeUpdate("drop table test_b");
st.executeUpdate("drop table test_c");
}
catch (Exception ex)
{
// We ignore any errors here
}
}
public metadata(String args[]) throws ClassNotFoundException, FileNotFoundException, IOException, SQLException
{
String url = args[0];
String usr = args[1];
String pwd = args[2];
// Load the driver
Class.forName("org.postgresql.Driver");
// Connect to database
System.out.println("Connecting to Database URL = " + url);
db = DriverManager.getConnection(url, usr, pwd);
dbmd = db.getMetaData();
st = db.createStatement();
// This prints the backend's version
System.out.println("Connected to " + dbmd.getDatabaseProductName() + " " + dbmd.getDatabaseProductVersion());
init();
System.out.println();
// Now the tests
if (doTest("Test DatabaseMetaData"))
doDatabaseMetaData();
if (doTest("Test ResultSetMetaData"))
doResultSetMetaData();
System.out.println("\nNow closing the connection");
st.close();
db.close();
cleanup();
}
/*
* This asks if the user requires to run a test.
*/
public boolean doTest(String s)
{
System.out.println();
System.out.print(s);
System.out.print(" Perform test? Y or N:");
System.out.flush();
char c = ' ';
try
{
while (!(c == 'n' || c == 'y' || c == 'N' || c == 'Y'))
{
c = (char)System.in.read();
}
}
catch (IOException ioe)
{
return false;
}
return c == 'y' || c == 'Y';
}
/*
* This displays a result set.
* Note: it closes the result once complete.
*/
public void displayResult(ResultSet rs) throws SQLException
{
ResultSetMetaData rsmd = rs.getMetaData();
int count = 0;
// Print the result column names
int cols = rsmd.getColumnCount();
for (int i = 1;i <= cols;i++)
System.out.print(rsmd.getColumnLabel(i) + (i < cols ? "\t" : "\n"));
// now the results
while (rs.next())
{
count++;
for (int i = 1;i <= cols;i++)
{
Object o = rs.getObject(i);
if (rs.wasNull())
System.out.print("{null}" + (i < cols ? "\t" : "\n"));
else
System.out.print(o.toString() + (i < cols ? "\t" : "\n"));
}
}
System.out.println("Result returned " + count + " rows.");
// finally close the result set
rs.close();
}
/*
* This process / commands (for now just /d)
*/
public void processSlashCommand(String line) throws SQLException
{
if (line.startsWith("\\d"))
{
if (line.startsWith("\\d "))
{
// Display details about a table
String table = line.substring(3);
displayResult(dbmd.getColumns(null, null, table, "%"));
}
else
{
String types[] = null;
if (line.equals("\\d"))
types = allUserTables;
else if (line.equals("\\di"))
types = usrIndices;
else if (line.equals("\\dt"))
types = usrTables;
else if (line.equals("\\ds"))
types = usrSequences;
else if (line.equals("\\dS"))
types = sysTables;
else
throw new SQLException("Unsupported \\d command: " + line);
// Display details about all system tables
//
// Note: the first two arguments are ignored. To keep to the spec,
// you must put null here
//
displayResult(dbmd.getTables(null, null, "%", types));
}
}
else
throw new SQLException("Unsupported \\ command: " + line);
}
private static final String allUserTables[] = {"TABLE", "INDEX", "SEQUENCE"};
private static final String usrIndices[] = {"INDEX"};
private static final String usrTables[] = {"TABLE"};
private static final String usrSequences[] = {"SEQUENCE"};
private static final String sysTables[] = {"SYSTEM TABLE", "SYSTEM INDEX"};
/*
* Display some instructions on how to run the example
*/
public static void instructions()
{
System.out.println("\nThis is not really an example, but is used to test the various methods in\nthe DatabaseMetaData and ResultSetMetaData classes.\n");
System.out.println("Useage:\n java example.metadata 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 debug items, don't put anything in\nhere.");
System.exit(1);
}
/*
* This little lot starts the test
*/
public static void main(String args[])
{
System.out.println("PostgreSQL metdata tester v6.4 rev 1\n");
if (args.length < 3)
instructions();
// This line outputs debug information to stderr. To enable this, simply
// add an extra parameter to the command line
if (args.length > 3)
DriverManager.setLogStream(System.err);
// Now run the tests
try
{
metadata test = new metadata(args);
}
catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex);
ex.printStackTrace();
}
}
}
package example;
import java.io.*;
import java.sql.*;
/*
* This example application demonstrates some of the drivers other features
* by implementing a simple psql replacement in Java.
*
*/
public class psql
{
Connection db; // The connection to the database
Statement st; // Our statement to run queries with
DatabaseMetaData dbmd; // This defines the structure of the database
boolean done = false; // Added by CWJ to permit \q command
public psql(String args[]) throws ClassNotFoundException, FileNotFoundException, IOException, SQLException
{
String url = args[0];
String usr = args[1];
String pwd = args[2];
// Load the driver
Class.forName("org.postgresql.Driver");
// Connect to database
System.out.println("Connecting to Database URL = " + url);
db = DriverManager.getConnection(url, usr, pwd);
dbmd = db.getMetaData();
st = db.createStatement();
// This prints the backend's version
System.out.println("Connected to " + dbmd.getDatabaseProductName() + " " + dbmd.getDatabaseProductVersion());
System.out.println();
// This provides us the means of reading from stdin
StreamTokenizer input = new StreamTokenizer(new InputStreamReader(System.in));
input.resetSyntax();
input.slashSlashComments(true); // allow // as a comment delimiter
input.eolIsSignificant(false); // treat eol's as spaces
input.wordChars(32, 126);
input.whitespaceChars(59, 59);
// input.quoteChar(39); *** CWJ: messes up literals in query string ***
// Now the main loop.
int tt = 0, lineno = 1;
while (tt != StreamTokenizer.TT_EOF && ! done)
{
System.out.print("[" + lineno + "] ");
System.out.flush();
// Here, we trap SQLException so they don't terminate the application
try
{
if ((tt = input.nextToken()) == StreamTokenizer.TT_WORD)
{
processLine(input.sval);
lineno++;
}
}
catch (SQLException ex)
{
System.out.println(ex.getMessage());
}
}
System.out.println("Now closing the connection");
st.close();
db.close();
}
/*
* This processes a statement
*/
public void processLine(String line) throws SQLException
{
if (line.startsWith("\\"))
{
processSlashCommand(line);
return ;
}
boolean type = st.execute(line);
boolean loop = true;
while (loop)
{
if (type)
{
// A ResultSet was returned
ResultSet rs = st.getResultSet();
displayResult(rs);
}
else
{
int count = st.getUpdateCount();
if (count == -1)
{
// This indicates nothing left
loop = false;
}
else
{
// An update count was returned
System.out.println("Updated " + st.getUpdateCount() + " rows");
}
}
if (loop)
type = st.getMoreResults();
}
}
/*
* This displays a result set.
* Note: it closes the result once complete.
*/
public void displayResult(ResultSet rs) throws SQLException
{
ResultSetMetaData rsmd = rs.getMetaData();
// Print the result column names
int cols = rsmd.getColumnCount();
for (int i = 1;i <= cols;i++)
System.out.print(rsmd.getColumnLabel(i) + (i < cols ? "\t" : "\n"));
// now the results
while (rs.next())
{
for (int i = 1;i <= cols;i++)
{
Object o = rs.getObject(i);
if (rs.wasNull())
System.out.print("{null}" + (i < cols ? "\t" : "\n"));
else
System.out.print(o.toString() + (i < cols ? "\t" : "\n"));
}
}
// finally close the result set
rs.close();
}
/*
* This process / commands (for now just /d)
*/
public void processSlashCommand(String line) throws SQLException
{
if (line.startsWith("\\d"))
{
if (line.startsWith("\\d "))
{
// Display details about a table
String table = line.substring(3);
displayResult(dbmd.getColumns(null, null, table, "%"));
}
else
{
String types[] = null;
if (line.equals("\\d"))
types = allUserTables;
else if (line.equals("\\di"))
types = usrIndices;
else if (line.equals("\\dt"))
types = usrTables;
else if (line.equals("\\ds"))
types = usrSequences;
else if (line.equals("\\dS"))
types = sysTables;
else
throw new SQLException("Unsupported \\d command: " + line);
// Display details about all system tables
//
// Note: the first two arguments are ignored. To keep to the spec,
// you must put null here
//
displayResult(dbmd.getTables(null, null, "%", types));
}
}
else if (line.equals("\\q")) // Added by CWJ to permit \q command
done = true;
else
throw new SQLException("Unsupported \\ command: " + line);
}
private static final String allUserTables[] = {"TABLE", "INDEX", "SEQUENCE"};
private static final String usrIndices[] = {"INDEX"};
private static final String usrTables[] = {"TABLE"};
private static final String usrSequences[] = {"SEQUENCE"};
private static final String sysTables[] = {"SYSTEM TABLE", "SYSTEM INDEX"};
/*
* Display some instructions on how to run the example
*/
public static void instructions()
{
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");
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.");
System.exit(1);
}
/*
* This little lot starts the test
*/
public static void main(String args[])
{
System.out.println("PostgreSQL psql example v6.3 rev 1\n");
if (args.length < 3)
instructions();
// This line outputs debug information to stderr. To enable this, simply
// add an extra parameter to the command line
if (args.length > 3)
DriverManager.setLogStream(System.err);
// Now run the tests
try
{
psql test = new psql(args);
}
catch (Exception ex)
{
System.err.println("Exception caught.\n" + ex);
ex.printStackTrace();
}
}
}
This diff is collapsed.
This diff is collapsed.
/*-------------------------------------------------------------------------
*
* PGConnection.java
* The public interface definition for a Postgresql Connection
* This interface defines PostgreSQL extentions to the java.sql.Connection
* interface. Any java.sql.Connection object returned by the driver will
* also implement this interface
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/PGConnection.java,v 1.7 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql;
import java.sql.*;
import org.postgresql.core.Encoding;
import org.postgresql.fastpath.Fastpath;
import org.postgresql.largeobject.LargeObjectManager;
public interface PGConnection
{
/**
* This method returns any notifications that have been received
* since the last call to this method.
* Returns null if there have been no notifications.
* @since 7.3
*/
public PGNotification[] getNotifications();
/**
* This returns the LargeObject API for the current connection.
* @since 7.3
*/
public LargeObjectManager getLargeObjectAPI() throws SQLException;
/**
* This returns the Fastpath API for the current connection.
* @since 7.3
*/
public Fastpath getFastpathAPI() throws SQLException;
/*
* This allows client code to add a handler for one of org.postgresql's
* more unique data types.
*
* <p><b>NOTE:</b> This is not part of JDBC, but an extension.
*
* <p>The best way to use this is as follows:
*
* <p><pre>
* ...
* ((org.postgresql.PGConnection)myconn).addDataType("mytype","my.class.name");
* ...
* </pre>
*
* <p>where myconn is an open Connection to org.postgresql.
*
* <p>The handling class must extend org.postgresql.util.PGobject
*
* @see org.postgresql.util.PGobject
*/
public void addDataType(String type, String name);
/** @deprecated */
public Encoding getEncoding() throws SQLException;
/** @deprecated */
public int getSQLType(String pgTypeName) throws SQLException;
/** @deprecated */
public int getSQLType(int oid) throws SQLException;
/** @deprecated */
public String getPGType(int oid) throws SQLException;
/** @deprecated */
public int getPGType(String typeName) throws SQLException;
/** @deprecated */
public Object getObject(String type, String value) throws SQLException;
}
/*-------------------------------------------------------------------------
*
* PGNotification.java
* This interface defines public PostgreSQL extention for Notifications
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/PGNotification.java,v 1.4 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql;
public interface PGNotification
{
/**
* Returns name of this notification
* @since 7.3
*/
public String getName();
/**
* Returns the process id of the backend process making this notification
* @since 7.3
*/
public int getPID();
}
/*-------------------------------------------------------------------------
*
* PGRefCursorResultSet.java
* Describes a PLPGSQL refcursor type.
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/PGRefCursorResultSet.java,v 1.2 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql;
/** A ref cursor based result set.
*/
public interface PGRefCursorResultSet
{
/** return the name of the cursor.
*/
public String getRefCursor ();
}
/*-------------------------------------------------------------------------
*
* PGStatement.java
* This interface defines PostgreSQL extentions to the java.sql.Statement
* interface. Any java.sql.Statement object returned by the driver will
* also implement this interface
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/PGStatement.java,v 1.8 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql;
import java.sql.*;
public interface PGStatement
{
/**
* Returns the Last inserted/updated oid.
* @return OID of last insert
* @since 7.3
*/
public long getLastOID() throws SQLException;
/**
* Turn on the use of prepared statements in the server (server side
* prepared statements are unrelated to jdbc PreparedStatements)
* @since 7.3
*/
public void setUseServerPrepare(boolean flag) throws SQLException;
/**
* Is this statement using server side prepared statements
* @since 7.3
*/
public boolean isUseServerPrepare();
}
/*-------------------------------------------------------------------------
*
* BaseConnection.java
* The internal interface definition for a jdbc connection
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/core/BaseConnection.java,v 1.5 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.core;
import java.sql.DatabaseMetaData;
import java.sql.Statement;
import java.sql.SQLException;
import org.postgresql.PGConnection;
import org.postgresql.PGNotification;
public interface BaseConnection extends PGConnection
{
public void addNotification(PGNotification p_notification);
public void addWarning(String msg);
public void cancelQuery() throws SQLException;
public Statement createStatement() throws SQLException;
public BaseResultSet execSQL(String s) throws SQLException;
public boolean getAutoCommit();
public String getCursorName() throws SQLException;
public Encoding getEncoding() throws SQLException;
public DatabaseMetaData getMetaData() throws SQLException;
public Object getObject(String type, String value) throws SQLException;
public int getPGProtocolVersionMajor();
public int getPGProtocolVersionMinor();
public PGStream getPGStream();
public String getPGType(int oid) throws SQLException;
public int getPGType(String pgTypeName) throws SQLException;
public int getSQLType(int oid) throws SQLException;
public int getSQLType(String pgTypeName) throws SQLException;
public boolean haveMinimumCompatibleVersion(String ver) throws SQLException;
public boolean haveMinimumServerVersion(String ver) throws SQLException;
public void setAutoCommit(boolean autoCommit) throws SQLException;
public void setCursorName(String cursor) throws SQLException;
}
/*-------------------------------------------------------------------------
*
* BaseResultSet.java
* The internal interface definition for a jdbc result set
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/core/BaseResultSet.java,v 1.3 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.core;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Vector;
public interface BaseResultSet
{
public BaseStatement getPGStatement();
public void append(BaseResultSet r);
public void close() throws SQLException;
public int getColumnCount();
public String getCursorName() throws SQLException;
public SimpleDateFormat getDateFormat();
public String getFixedString(int col) throws SQLException;
public long getLastOID();
public ResultSetMetaData getMetaData() throws SQLException;
public ResultSet getNext();
public Object getObject(int columnIndex) throws SQLException;
public int getResultCount();
public String getStatusString();
public String getString(int columnIndex) throws SQLException;
public StringBuffer getStringBuffer();
public SimpleDateFormat getTimestampFormat();
public SimpleDateFormat getTimestampTZFormat();
public int getTupleCount();
public boolean next() throws SQLException;
public boolean reallyResultSet();
public void reInit (Field[] fields, Vector tuples, String status,
int updateCount, long insertOID, boolean binaryCursor);
public void setStatement(BaseStatement statement);
}
/*-------------------------------------------------------------------------
*
* BaseStatement.java
* The internal interface definition for a jdbc statement
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/core/BaseStatement.java,v 1.7 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.core;
import org.postgresql.PGRefCursorResultSet;
import java.sql.*;
import java.util.Vector;
public interface BaseStatement extends org.postgresql.PGStatement
{
public BaseResultSet createResultSet(Field[] fields, Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor) throws SQLException;
public PGRefCursorResultSet createRefCursorResultSet(String cursorName) throws SQLException;
public BaseConnection getPGConnection();
/*
* The maxRows limit is set to limit the number of rows that
* any ResultSet can contain. If the limit is exceeded, the
* excess rows are silently dropped.
*/
public void addWarning(String p_warning) throws SQLException;
public void close() throws SQLException;
public int getFetchSize();
public int getMaxFieldSize() throws SQLException;
public int getMaxRows() throws SQLException;
public int getResultSetConcurrency() throws SQLException;
public String getFetchingCursorName();
public SQLWarning getWarnings() throws SQLException;
public void setMaxFieldSize(int max) throws SQLException;
}
This diff is collapsed.
/*-------------------------------------------------------------------------
*
* Field.java
* Field is a class used to describe fields in a PostgreSQL ResultSet
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/core/Field.java,v 1.3 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.core;
import java.sql.*;
import org.postgresql.core.BaseConnection;
/*
*/
public class Field
{
private int length; // Internal Length of this field
private int oid; // OID of the type
private int mod; // type modifier of this field
private String name; // Name of this field
private BaseConnection conn; // Connection Instantation
/*
* Construct a field based on the information fed to it.
*
* @param conn the connection this field came from
* @param name the name of the field
* @param oid the OID of the field
* @param len the length of the field
*/
public Field(BaseConnection conn, String name, int oid, int length, int mod)
{
this.conn = conn;
this.name = name;
this.oid = oid;
this.length = length;
this.mod = mod;
}
/*
* Constructor without mod parameter.
*
* @param conn the connection this field came from
* @param name the name of the field
* @param oid the OID of the field
* @param len the length of the field
*/
public Field(BaseConnection conn, String name, int oid, int length)
{
this(conn, name, oid, length, 0);
}
/*
* @return the oid of this Field's data type
*/
public int getOID()
{
return oid;
}
/*
* @return the mod of this Field's data type
*/
public int getMod()
{
return mod;
}
/*
* @return the name of this Field's data type
*/
public String getName()
{
return name;
}
/*
* @return the length of this Field's data type
*/
public int getLength()
{
return length;
}
/*
* We also need to get the PG type name as returned by the back end.
*
* @return the String representation of the PG type of this field
* @exception SQLException if a database access error occurs
*/
public String getPGType() throws SQLException
{
return conn.getPGType(oid);
}
/*
* We also need to get the java.sql.types type.
*
* @return the int representation of the java.sql.types type of this field
* @exception SQLException if a database access error occurs
*/
public int getSQLType() throws SQLException
{
return conn.getSQLType(oid);
}
}
/*-------------------------------------------------------------------------
*
* Notification.java
* This is the implementation of the PGNotification interface
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/core/Notification.java,v 1.4 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.core;
import org.postgresql.PGNotification;
public class Notification implements PGNotification
{
public Notification(String p_name, int p_pid)
{
m_name = p_name;
m_pid = p_pid;
}
/*
* Returns name of this notification
*/
public String getName()
{
return m_name;
}
/*
* Returns the process id of the backend process making this notification
*/
public int getPID()
{
return m_pid;
}
private String m_name;
private int m_pid;
}
This diff is collapsed.
This diff is collapsed.
# This is the french version of some errors. Errors not in this file
# are handled by the parent errors.properties file.
postgresql.jvm.version:Le fichier de postgresql.jar ne contient pas les classes correctes de JDBC pour ce JVM. Try que rebuilding.\nException jetées était {0}
postgresql.metadata.unavailable: Les métadonnées ne sont pas disponibles.
postgresql.unusual:Quelque chose de peu commun s'est produit pour faire échouer le gestionnaire. Veuillez enregistrer cette exception: {0}
postgresql.unimplemented:Cette méthode n'est pas encore appliquée.
package org.postgresql.jdbc1;
import java.sql.*;
import java.util.Vector;
import org.postgresql.PGRefCursorResultSet;
import org.postgresql.core.BaseResultSet;
import org.postgresql.core.Field;
public class Jdbc1CallableStatement extends AbstractJdbc1Statement implements java.sql.CallableStatement
{
public Jdbc1CallableStatement(Jdbc1Connection connection, String sql) throws SQLException
{
super(connection, sql);
}
public BaseResultSet createResultSet (Field[] fields, java.util.Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor) throws SQLException
{
return new Jdbc1ResultSet(this, fields, tuples, status, updateCount, insertOID, binaryCursor);
}
public PGRefCursorResultSet createRefCursorResultSet (String cursorName) throws SQLException
{
return new Jdbc1RefCursorResultSet(this, cursorName);
}
}
package org.postgresql.jdbc1;
import java.sql.*;
import java.util.*;
import org.postgresql.core.Field;
import org.postgresql.util.PSQLException;
public class Jdbc1DatabaseMetaData extends AbstractJdbc1DatabaseMetaData implements java.sql.DatabaseMetaData
{
public Jdbc1DatabaseMetaData(Jdbc1Connection conn)
{
super(conn);
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment