Approaches to Web Development for Bioinformatics

Previous  Contents  Next
References

Accessing a Relational Database with Java

Java supports access to relational databases via several interfaces, the most commonly used of which is the Java Database Connectivity (JDBC) API. This API is an integral part of the base Java platform. The JDBC API is documented on the Sun website16. Drivers for different databases each implement this API and bundle the driver as a jar file. The one that I will demonstrate here is for MySQL. You can read about and download the MySQL JDBC driver, MySQL Connector/J, at the MySQL web site40. Make sure that you have it on your class path when you run the code.

Here is an example Java program that retrieves the complete list of gene_info records in the table defined about and prints them out to the console. The Java code is in file GeneInfoDAO.java. The compiled code is in file GeneInfoDAO.class. The program should be run from the command line in stand-alone mode. Don't forget to replace the name and password of the user in your version.


import java.sql.*;

/**
* Class to demonstrate use of JDBC API
*/
public class GeneInfoDAO {

/**
* Print out gene information from the gene_info table
*/
public void printGeneInfo() {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {

// Register driver
Class.forName("com.mysql.jdbc.Driver");

conn = DriverManager.getConnection(
"jdbc:mysql://localhost/genes?" +
"user={USER_ABC}&password={ABC}");
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM gene_info");
while (rs.next()) {
int id = rs.getInt("id");
String symbol = rs.getString("symbol");
String name = rs.getString("name");
System.out.println("Gene, id: " + id + ", symbol: " + symbol + ", name: " + name);
}
} catch (SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
System.err.println("ClassNotFoundException: " + ex.getMessage());
ex.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch(Throwable t) {}
}
if (stmt != null) {
try {
stmt.close();
} catch(Throwable t) {}
}
if (conn != null) {
try {
conn.close();
} catch(Throwable t) {}
}
}
}

// Entry point
public static void main(String[] argv) {
GeneInfoDAO geneInfoDAO = new GeneInfoDAO();
geneInfoDAO.printGeneInfo();
}
}

A few things are apparent from this example:


Previous  Contents  Next
References

Contributed Comments and NotesAdd a comment.

There are no user comments.

Google

Please send ideas and opinions by email at alexamies@gmail.com.

© 2006-2007 Alex Amies