Using More Advanced JDBC Features, Page 4
Closing the Connection
Finally, you need to close the connection. This is another point where I ran into some confusion. Just as when I failed to commit the transaction, failing to close the connection can lead to the same problem. In some cases, the changes to the database were not permanent until the connection was closed. This is accomplished with the single line of code:
DBConnection.close();
The complete code for this method is presented in Listing 11.
Listing 11
public void closeConnection(){
try {
DBConnection.close();
System.out.println ("+++++++++++++++++++++");
System.out.println ("+ connection closed +");
System.out.println ("+++++++++++++++++++++");
} catch (Exception excep) {
System.out.println ("Unable to close connection: n" + excep);
System.exit(0);
}
}
Conclusion
In this article, you further explored the basic concepts involved with connecting to a database from a Java application using JDBC. The concepts covered in this article provide a strong framework for just about any database application that you may want to develop.
Although this code works on an Microsoft Access database on a Microsoft Windows platform, there are changes required to connect to and use another database. This is true whether using a completely different database on Microsoft Windows or another database on a non-Windows platform.
Download the Code
Download the accompanying database here.
References
- Gilbert, Stephen, and Bill McCarty: Object-Oriented Design in Java. The Waite Group, 1998.
- Tyma, Paul, Gabriel Torok and Troy Downing:Java Primer Plus. The Waite Group, 1996.
- Jaworski, Jamie: Java 1.1 Developers Guide. Sams Publishing, 1997.
- www.javasoft.com
- http://msdn2.microsoft.com/en-us/library/cf131f6b.aspx
About the Author
Matt Weisfeld is a faculty member at Cuyahoga Community College (Tri-C) in Cleveland, Ohio. Matt is a member of the Information Technology department, teaching programming languages such as C++, Java, and C# .NET as well as various web technologies. Prior to joining Tri-C, Matt spent 20 years in the information technology industry gaining experience in software development, project management, business development, corporate training, and part-time teaching. Matt holds an MS in computer science and an MBA in project management. Besides The Object-Oriented Thought Process
, which is now in it's second edition, Matt has published two other computer books, and more than a dozen articles in magazines and journals such as Dr. Dobb's Journal, The C/C++ Users Journal, Software Development Magazine, Java Report, and the international journal Project Management. Matt has presented at conferences throughout the United States and Canada.
