Chemistry Reference
In-Depth Information
There are other methods to execute SQL queries and fetch results, but
these are described elsewhere. 16
5.5.4 Java
Java is a general-purpose computer language that includes the java.sql
package. 17 This package is part of the standard java distribution from
Sun and provides a generic interface to an RDBMS. JDBC (Java Database
Connectivity) is a separate driver that enables communication between
java.sql and a variety of RDBMS. The driver is in the form of a jar file. A
separate driver is needed to enable java communication with each dif-
ferent RDBMS. The PostgreSQL JDBC driver 18 is used in the following
example. It must be downloaded and installed in order for the following
example to work properly.
import java.sql.*;
public class JDBCDemo {
public static void main( String[] args ) {
try {
// Connect to the database
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://rigel/book";
Connection con = DriverManager.getConnection(url, "reader");
// Execute the SQL statement
Statement stmt = con.createStatement();
ResultSet resultSet = stmt.executeQuery("SELECT
smiles,cas from nci.structure where gnova.
matches(smiles,'c1ccccc1C(=O)NC')");
System.out.println("Got results!");
// Loop thru all the rows
while( resultSet.next() ) {
String smi = resultSet.getString( "smiles" );
String cas = resultSet.getString( "cas" );
System.out.println( smi + "\t" + cas );
}
stmt.close();
}
catch( Exception e ) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
Once this is compiled, it can be run as follows, being sure that the
PostgreSQL JDBC jar file is in the class path. The exact location of the jar
file may be different than in the example here.
java -cp .:/usr/share/java/postgresql.jar JDBCDemo
Search WWH ::




Custom Search