Before We Start Coding In order to do some hands on coding, you need to have access to the following:
- A database management system, such as Microsoft Access
- A JDBC driver
If you don't have access to a DBMS, you can download the open source MySQL database at http://www.mysql.com. You can also download the JDBC driver for MySQL from this site.
[Note] You need to have the driver classes in your CLASSPATH statement in order to load the driver. [End Note]
A simple example
What's better than developing a small application to drill down into JDBC programming! Lets develop a small address book application that has the following features:
- Lets you create the address book table
- Lets you add an entry to the book
- Lets you search for an entry in the book
This simple application will let us demonstrate the use of various JDBC classes and different types of SQL statements. It uses a database named "test_db" without any user ID or password. The database driver used is a type 4 driver for MySQL, however you can replace it with any other JDBC driver of your choice.
A word of caution: do not be overwhelmed by the lines of code below. Instead, concentrate on the core logic. Also, this is just a sample application to demonstrate the steps involved in JDBC programming. It's not designed for a production system.
Having said that, lets get started:
// AddressBookEntry.java
/** Class to represent an addressbook entry. */
public class AddressBookEntry {
/** The nickname. */
private String nickName;
/** The name. */
private String name;
/** The email. */
private String email;
/** Initializes an entry. */
public AddressBookEntry(String nickName, String name, String email) {
this.nickName = nickName;
this.name = name;
this.email = email;
}
/** Returns the nickname. */
public String getNickName() {
return nickName;
}
/** Returns the name. */
public String getName() {
return name;
}
/** Returns the email. */
public String getEmail() {
return email;
}
/** Sets the nickname. */
public void setNickName(String nickName) {
this.nickName = nickName;
}
/** Sets the name. */
public void setName(String name) {
this.name = name;
}
/** Sets the email. */
public void setEmail(String email) {
this.email = email;
}
/** Returns a string representation of the entry. */
public String toString() {
// The return value
StringBuffer buf = new StringBuffer();
buf.append("Nickname: ");
buf.append(nickName);
buf.append(", Name: " );
buf.append(name);
buf.append(", Email: ");
buf.append(email);
return buf.toString();
}
}
Our Address Book App (contd.) Nitin runs http://www.TechnoBuff.com, which provides Java developers will the tools, articles and resources they need to succeed. Many more Java, ASP, PHP, .NET, and C++ articles like this one are available at http://www.devarticles.com. If you're in search of free scripts to help make your life as a developer easier, why not check out http://www.devscripts.com.
No comments yet. Be the first to comment!