next up previous contents index
Next: Scripting Languages Up: Programming Interfaces Previous: ODBC

  
Java (JDBC)

Figure [*] shows a Java version of the same application.  

        
        /*
         *  Java sample program
         */
         
        import java.io.*;
        import java.sql.*;
         
        public class sample
        {
            Connection  conn;                                   // holds database connection
            Statement   stmt;                                   // holds SQL statement
            String      state_code;                             // holds state code entered by user
         
            public sample() throws ClassNotFoundException, FileNotFoundException, IOException, SQLException
            {
                Class.forName("org.postgresql.Driver");         // load database interface
                                                                // connect to the database
                conn = DriverManager.getConnection("jdbc:postgresql:test", "testuser", "");
                stmt = conn.createStatement();
         
                System.out.print("Enter a state code:  ");      // prompt user for a state code
                System.out.flush();
                BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
                state_code = r.readLine();
         
                ResultSet res = stmt.executeQuery(              // send the query
                    "SELECT name " +
                    "FROM statename " +
                    "WHERE code = '" + state_code + "'");
         
                if (res != null) 
                    while(res.next()) 
                    {
                        String state_name = res.getString(1);
                        System.out.println(state_name);
                    }
         
                res.close();
                stmt.close();
                conn.close();
            }
         
            public static void main(String args[])
            {
                try {
                    sample test = new sample();
                } catch(Exception exc) 
                {
                    System.err.println("Exception caught.\n" + exc);
                    exc.printStackTrace();
                }
            }
        }
        
 

The interface's source code is located in pgsql/src/interfaces/jdbc. Once the interface is compiled, the file postgresql.jar should be copied to the directory containing the other jar  files. The full path name of postgresql.jar must then be added to the CLASSPATH environment variable.

Java programs are compiled using javac  and run using java. Java is both a compiled and interpreted language. It is compiled for speed, but interpreted when executed so that any computer can run the compiled program.  


Bruce Momjian
2001-05-09