mirror of
https://github.com/postgres/postgres.git
synced 2025-08-21 10:42:50 +03:00
Oops...missed over half the patch :(
This commit is contained in:
377
src/interfaces/jdbc/example/ImageViewer.java
Normal file
377
src/interfaces/jdbc/example/ImageViewer.java
Normal file
@@ -0,0 +1,377 @@
|
||||
package example;
|
||||
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import java.io.*;
|
||||
import java.sql.*;
|
||||
import postgresql.largeobject.*;
|
||||
|
||||
/**
|
||||
* This example is a small application that stores and displays images
|
||||
* held on a postgresql database.
|
||||
*
|
||||
* Before running this application, you need to create a database, and
|
||||
* on the first time you run it, select "Initialise" in the "PostgreSQL"
|
||||
* menu.
|
||||
*
|
||||
* Important note: You will notice we import the postgresql.largeobject
|
||||
* package, but don't import the postgresql package. The reason for this is
|
||||
* that importing postgresql can confuse javac (we have conflicting class names
|
||||
* in postgresql.* and java.sql.*). This doesn't cause any problems, as long
|
||||
* as no code imports 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 ImageViewer implements ItemListener
|
||||
{
|
||||
Connection db;
|
||||
Statement stat;
|
||||
LargeObjectManager lom;
|
||||
Frame frame;
|
||||
Label label; // Label used to display the current name
|
||||
List list; // The list of available images
|
||||
imageCanvas canvas; // Canvas used to display the image
|
||||
String currentImage; // The current images name
|
||||
|
||||
// This is a simple component to display our image
|
||||
public class imageCanvas extends Canvas
|
||||
{
|
||||
private Image image;
|
||||
|
||||
public imageCanvas()
|
||||
{
|
||||
image=null;
|
||||
}
|
||||
|
||||
public void setImage(Image img)
|
||||
{
|
||||
image=img;
|
||||
repaint();
|
||||
}
|
||||
|
||||
// This defines our minimum size
|
||||
public Dimension getMinimumSize()
|
||||
{
|
||||
return new Dimension(400,400);
|
||||
}
|
||||
|
||||
public Dimension getPreferedSize()
|
||||
{
|
||||
return getMinimumSize();
|
||||
}
|
||||
|
||||
public void update(Graphics g)
|
||||
{
|
||||
paint(g);
|
||||
}
|
||||
|
||||
public void paint(Graphics g)
|
||||
{
|
||||
g.setColor(Color.gray);
|
||||
g.fillRect(0,0,getSize().width,getSize().height);
|
||||
|
||||
if(image!=null)
|
||||
g.drawImage(image,0,0,this);
|
||||
}
|
||||
}
|
||||
|
||||
public ImageViewer(Frame f,String url,String user,String password) throws ClassNotFoundException, FileNotFoundException, IOException, SQLException
|
||||
{
|
||||
frame = f;
|
||||
|
||||
MenuBar mb = new MenuBar();
|
||||
Menu m;
|
||||
MenuItem i;
|
||||
|
||||
f.setMenuBar(mb);
|
||||
mb.add(m = new Menu("PostgreSQL"));
|
||||
m.add(i= new MenuItem("Initialise"));
|
||||
i.addActionListener(new ActionListener() {
|
||||
public void actionPerformed(ActionEvent e) {
|
||||
ImageViewer.this.init();
|
||||
}
|
||||
});
|
||||
|
||||
m.add(i= new MenuItem("Exit"));
|
||||
ActionListener exitListener = new ActionListener() {
|
||||
public void actionPerformed(ActionEvent e) {
|
||||
ImageViewer.this.close();
|
||||
}
|
||||
};
|
||||
m.addActionListener(exitListener);
|
||||
|
||||
mb.add(m = new Menu("Image"));
|
||||
m.add(i= new MenuItem("Import"));
|
||||
ActionListener importListener = new ActionListener() {
|
||||
public void actionPerformed(ActionEvent e) {
|
||||
ImageViewer.this.importImage();
|
||||
}
|
||||
};
|
||||
i.addActionListener(importListener);
|
||||
|
||||
m.add(i= new MenuItem("Remove"));
|
||||
ActionListener removeListener = new ActionListener() {
|
||||
public void actionPerformed(ActionEvent e) {
|
||||
ImageViewer.this.removeImage();
|
||||
}
|
||||
};
|
||||
i.addActionListener(removeListener);
|
||||
|
||||
// To the north is a label used to display the current images name
|
||||
f.add("North",label = new Label());
|
||||
|
||||
// We have a panel to the south of the frame containing the controls
|
||||
Panel p = new Panel();
|
||||
p.setLayout(new FlowLayout());
|
||||
Button b;
|
||||
p.add(b=new Button("Refresh List"));
|
||||
b.addActionListener(new ActionListener() {
|
||||
public void actionPerformed(ActionEvent e) {
|
||||
ImageViewer.this.refreshList();
|
||||
}
|
||||
});
|
||||
p.add(b=new Button("Import new image"));
|
||||
b.addActionListener(importListener);
|
||||
p.add(b=new Button("Remove image"));
|
||||
b.addActionListener(removeListener);
|
||||
p.add(b=new Button("Quit"));
|
||||
b.addActionListener(exitListener);
|
||||
f.add("South",p);
|
||||
|
||||
// And a panel to the west containing the list of available images
|
||||
f.add("West",list=new List());
|
||||
list.addItemListener(this);
|
||||
|
||||
// Finally the centre contains our image
|
||||
f.add("Center",canvas = new imageCanvas());
|
||||
|
||||
// Load the driver
|
||||
Class.forName("postgresql.Driver");
|
||||
|
||||
// Connect to database
|
||||
System.out.println("Connecting to Database URL = " + url);
|
||||
db = DriverManager.getConnection(url, user, password);
|
||||
|
||||
// Create a statement
|
||||
stat = db.createStatement();
|
||||
|
||||
// Also, get the LargeObjectManager for this connection
|
||||
lom = ((postgresql.Connection)db).getLargeObjectAPI();
|
||||
|
||||
// Now refresh the image selection list
|
||||
refreshList();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* This method initialises the database by creating a table that contains
|
||||
* the image names, and Large Object OID's
|
||||
*/
|
||||
public void init()
|
||||
{
|
||||
try {
|
||||
stat.executeUpdate("create table images (imgname name,imgoid oid)");
|
||||
label.setText("Initialised database");
|
||||
} catch(SQLException ex) {
|
||||
label.setText(ex.toString());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This closes the connection, and ends the application
|
||||
*/
|
||||
public void close()
|
||||
{
|
||||
try {
|
||||
db.close();
|
||||
} catch(SQLException ex) {
|
||||
System.err.println(ex.toString());
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* This imports an image into the database.
|
||||
*
|
||||
* This is the most efficient method, using the large object extension.
|
||||
*/
|
||||
public void importImage()
|
||||
{
|
||||
FileDialog d = new FileDialog(frame,"Import Image",FileDialog.LOAD);
|
||||
d.setVisible(true);
|
||||
String name = d.getFile();
|
||||
String dir = d.getDirectory();
|
||||
d.dispose();
|
||||
|
||||
// Now the real import stuff
|
||||
if(name!=null && dir!=null) {
|
||||
try {
|
||||
System.out.println("Importing file");
|
||||
// A temporary buffer - this can be as large as you like
|
||||
byte buf[] = new byte[2048];
|
||||
|
||||
// Open the file
|
||||
System.out.println("Opening file "+dir+"/"+name);
|
||||
FileInputStream fis = new FileInputStream(new File(dir,name));
|
||||
|
||||
// Gain access to large objects
|
||||
System.out.println("Gaining LOAPI");
|
||||
|
||||
// Now create the large object
|
||||
System.out.println("creating blob");
|
||||
int oid = lom.create();
|
||||
|
||||
System.out.println("Opening "+oid);
|
||||
LargeObject blob = lom.open(oid);
|
||||
|
||||
// Now copy the file into the object.
|
||||
//
|
||||
// Note: we dont use write(buf), as the last block is rarely the same
|
||||
// size as our buffer, so we have to use the amount read.
|
||||
System.out.println("Importing file");
|
||||
int s,t=0;
|
||||
while((s=fis.read(buf,0,buf.length))>0) {
|
||||
System.out.println("Block s="+s+" t="+t);t+=s;
|
||||
blob.write(buf,0,s);
|
||||
}
|
||||
|
||||
// Close the object
|
||||
System.out.println("Closing blob");
|
||||
blob.close();
|
||||
|
||||
// Now store the entry into the table
|
||||
stat.executeUpdate("insert into images values ('"+name+"',"+oid+")");
|
||||
stat.close();
|
||||
|
||||
// Finally refresh the names list, and display the current image
|
||||
refreshList();
|
||||
displayImage(name);
|
||||
} catch(Exception ex) {
|
||||
label.setText(ex.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This refreshes the list of available images
|
||||
*/
|
||||
public void refreshList()
|
||||
{
|
||||
try {
|
||||
// First, we'll run a query, retrieving all of the image names
|
||||
ResultSet rs = stat.executeQuery("select imgname from images order by imgname");
|
||||
if(rs!=null) {
|
||||
list.removeAll();
|
||||
while(rs.next())
|
||||
list.addItem(rs.getString(1));
|
||||
rs.close();
|
||||
}
|
||||
} catch(SQLException ex) {
|
||||
label.setText(ex.toString()+" Have you initialised the database?");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This removes an image from the database
|
||||
*
|
||||
* Note: With postgresql, this is the only way of deleting a large object
|
||||
* using Java.
|
||||
*/
|
||||
public void removeImage()
|
||||
{
|
||||
try {
|
||||
// Delete any large objects for the current name
|
||||
ResultSet rs = stat.executeQuery("select imgoid from images where imgname='"+currentImage+"'");
|
||||
if(rs!=null) {
|
||||
// Even though there should only be one image, we still have to
|
||||
// cycle through the ResultSet
|
||||
while(rs.next()) {
|
||||
System.out.println("Got oid "+rs.getInt(1));
|
||||
lom.delete(rs.getInt(1));
|
||||
System.out.println("Import complete");
|
||||
}
|
||||
}
|
||||
rs.close();
|
||||
|
||||
// Finally delete any entries for that name
|
||||
stat.executeUpdate("delete from images where imgname='"+currentImage+"'");
|
||||
|
||||
label.setText(currentImage+" deleted");
|
||||
currentImage=null;
|
||||
refreshList();
|
||||
} catch(SQLException ex) {
|
||||
label.setText(ex.toString());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This displays an image from the database.
|
||||
*
|
||||
* For images, this is the easiest method.
|
||||
*/
|
||||
public void displayImage(String name)
|
||||
{
|
||||
try {
|
||||
System.out.println("Selecting oid for "+name);
|
||||
ResultSet rs = stat.executeQuery("select imgoid from images where imgname='"+name+"'");
|
||||
if(rs!=null) {
|
||||
// Even though there should only be one image, we still have to
|
||||
// cycle through the ResultSet
|
||||
while(rs.next()) {
|
||||
System.out.println("Got oid "+rs.getInt(1));
|
||||
canvas.setImage(canvas.getToolkit().createImage(rs.getBytes(1)));
|
||||
System.out.println("Import complete");
|
||||
label.setText(currentImage = name);
|
||||
}
|
||||
}
|
||||
rs.close();
|
||||
} catch(SQLException ex) {
|
||||
label.setText(ex.toString());
|
||||
}
|
||||
}
|
||||
|
||||
public void itemStateChanged(ItemEvent e) {
|
||||
displayImage(list.getItem(((Integer)e.getItem()).intValue()));
|
||||
}
|
||||
|
||||
/**
|
||||
* This is the command line instructions
|
||||
*/
|
||||
public static void instructions()
|
||||
{
|
||||
System.err.println("java example.ImageViewer jdbc-url user password");
|
||||
System.err.println("\nExamples:\n");
|
||||
System.err.println("java -Djdbc.driver=postgresql.Driver example.ImageViewer jdbc:postgresql:test postgres password\n");
|
||||
|
||||
System.err.println("This example tests the binary large object api of the driver.\nBasically, it will allow you to store and view images held in the database.");
|
||||
System.err.println("Note: If you are running this for the first time on a particular database,\nyou have to select \"Initialise\" in the \"PostgreSQL\" menu.\nThis will create a table used to store image names.");
|
||||
}
|
||||
|
||||
/**
|
||||
* This is the application entry point
|
||||
*/
|
||||
public static void main(String args[])
|
||||
{
|
||||
if(args.length!=3) {
|
||||
instructions();
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
try {
|
||||
Frame frame = new Frame("PostgreSQL ImageViewer v6.3 rev 1");
|
||||
frame.setLayout(new BorderLayout());
|
||||
ImageViewer viewer = new ImageViewer(frame,args[0],args[1],args[2]);
|
||||
frame.pack();
|
||||
frame.setVisible(true);
|
||||
} catch(Exception ex) {
|
||||
System.err.println("Exception caught.\n"+ex);
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
172
src/interfaces/jdbc/example/basic.java
Normal file
172
src/interfaces/jdbc/example/basic.java
Normal file
@@ -0,0 +1,172 @@
|
||||
package example;
|
||||
|
||||
import java.io.*;
|
||||
import java.sql.*;
|
||||
import java.text.*;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
*/
|
||||
|
||||
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("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();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 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)");
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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();
|
||||
}
|
||||
}
|
||||
}
|
194
src/interfaces/jdbc/example/blobtest.java
Normal file
194
src/interfaces/jdbc/example/blobtest.java
Normal file
@@ -0,0 +1,194 @@
|
||||
package example;
|
||||
|
||||
import java.io.*;
|
||||
import java.sql.*;
|
||||
import 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 postgresql.largeobject
|
||||
* package, but don't import the postgresql package. The reason for this is
|
||||
* that importing postgresql can confuse javac (we have conflicting class names
|
||||
* in postgresql.* and java.sql.*). This doesn't cause any problems, as long
|
||||
* as no code imports 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("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");
|
||||
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");
|
||||
|
||||
// Internally, the driver provides JDBC compliant methods to access large
|
||||
// objects, however the unique methods available to postgresql makes things
|
||||
System.out.println("Gaining access to large object api");
|
||||
lobj = ((postgresql.Connection)db).getLargeObjectAPI();
|
||||
|
||||
int oid = ownapi_test1();
|
||||
ownapi_test2(oid);
|
||||
//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);
|
||||
}
|
||||
|
||||
//=========================================================================
|
||||
|
||||
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=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=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 v6.3 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();
|
||||
}
|
||||
}
|
||||
}
|
181
src/interfaces/jdbc/example/datestyle.java
Normal file
181
src/interfaces/jdbc/example/datestyle.java
Normal file
@@ -0,0 +1,181 @@
|
||||
package example;
|
||||
|
||||
import java.io.*;
|
||||
import java.sql.*;
|
||||
import java.text.*;
|
||||
|
||||
/**
|
||||
* 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("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();
|
||||
}
|
||||
}
|
||||
}
|
210
src/interfaces/jdbc/example/psql.java
Normal file
210
src/interfaces/jdbc/example/psql.java
Normal file
@@ -0,0 +1,210 @@
|
||||
package example;
|
||||
|
||||
import java.io.*;
|
||||
import java.sql.*;
|
||||
import java.text.*;
|
||||
|
||||
/**
|
||||
* 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
|
||||
|
||||
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("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);
|
||||
|
||||
// Now the main loop.
|
||||
int tt=0,lineno=1;
|
||||
while(tt!=StreamTokenizer.TT_EOF) {
|
||||
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(rs.getObject(i).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
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user