Main Content

Bean Classes in Java and Java Database Connections

Archive - Originally posted on "The Horse's Mouth" - 2009-05-02 08:25:27 - Graham Ellis

A class is a bean if it has a constructor that takes no parameters, and if it has methods that start with "get" to read properties, and "set" to set properties. And it's a good idea (!) if the letter after the word get or set is a capital, as this will let it be used within JSP tag libraries. Bean classes may have other methods too ... it's just that they won't be accessible through the bean interface.


Here's an example of using JDBC to connect to a MySQL database ... from within the code of a bean. Although Java has manager support to connect to databases, it doesn't include the actual support for any specific database - you need to go and download separate packages of classes for that. "How frustrating" you may say (you would be right!) but it means that the Java folks can look after the Java, the database folks can look after the databases, and when a database is updated the user doesn't have to wait for the next release of Java before he can use the new facilities. It also avoids huge arguments in the community about what should (and should not) be included as a standard driver.

So the database manager as shipped is rather like building a hotel without guests, and the individual drivers you load are like the guests. You need the hotel for the guests, but until you have guests it's really not fulfilling any sensible purpose.

Once the classes are there, how does the connectivity work? Here are the steps that we used in the example show here, written during yesterday's course:

Class.forName("xxxx").newInstance();
where xxxx is the driver class
Loads in the driver class into the driver manager

Connection cnamedb = driverManager.getConnection("yyyy");
where yyyy is a pseudoURL which describes the connection
Log in to the appropriate database

Statement bdstate = cnamedb.createStatement();
Get ready to perform an access (query) to the database

ResultSet dbresult = bdstate.executeQuery("zzzz");
where zzzz is the SQL query to be run
Run the actual query - or rather start it, and return an object that will let you iterate through the result

while (dbresult.next()) { Value = dbresult.getString("wwww"); }
where wwww is the field (column) that you want
Extract the data that you want from each row in turn. ... you can now add your code to process the Value variable further ...

Java Database Connections are also covered on our Java Bootcamp and Learning to Program in Java courses.