December 18, 2014
Hot Topics:

Connecting to a Database with JDBC

  • December 16, 2005
  • By Matt Weisfeld
  • Send Email »
  • More Articles »

You create a single string that you will use to append all information that you want to output. That string can be written to either the screen or a file. To make things more interesting, you can create a document with XML-like tags using the column name as the tag names. You will use this technique in future columns when you learn about XML parsing. An XML tag would look like this:

<Name>Baseball</Name>

Listing 5 shows the complete displayResults( ) method.

// Display the Results
void displayResults(ResultSet rs) throws SQLException {
   ResultSetMetaData metaData = rs.getMetaData();
   int columns=metaData.getColumnCount();
   String text="";

   while(rs.next()){
      for(int i=1;i<=columns;++i) {
         text+="<"+metaData.getColumnName(i)+">";
         text+=rs.getString(i);
         text+="</"+metaData.getColumnName(i)+">";
         text+="n";
      }
      text+="n";
   }
   System.out.println(text);
}

Listing 5

Considering the powerful functionality that you have covered, there really is not that much code involved. Although hard coding the SQL statement is obviously not extensible, you can use this technique to verify that you have successfully connected and interacted with the database. The complete code for this application is presented in Listing 6. When we run this application and successfully connect to the purchaseOrder database, the output in Figure 10 is produced. Note that it is in pseudo XML-like tags. In later installments, you will complete the generation process of complete XML documents.

// JDBC|Test – complete code
public class JDBCTest {

   public static void main(String args[]){

      RunDB runDB = new RunDB();

      try{
         runDB.loadDriver();
         runDB.makeConnection();
         runDB.buildStatement();
         runDB.executeQuery();
      }catch(Exception e){
         e.printStackTrace();
      }

   }
}

//RunDB
import java.sql.*;

public class RunDB {

   Connection connection;
   Statement statement;

   public void loadDriver() throws ClassNotFoundException{
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
   }

   public void makeConnection() throws SQLException {
      connection=
         DriverManager.getConnection("jdbc:odbc:purchaseOrder")
   }

   public void buildStatement() throws SQLException {
      statement = connection.createStatement();
   }

   public void executeQuery() throws SQLException {

      boolean foundResults =
         statement.execute("SELECT * FROM Transaction");
      if(foundResults){
         ResultSet set = statement.getResultSet();
         if(set!=null) displayResults(set);
      }else {
         connection.close();
      }
   }

   void displayResults(ResultSet rs) throws SQLException {
      ResultSetMetaData metaData = rs.getMetaData();
      int columns=metaData.getColumnCount();
      String text="";

      while(rs.next()){
         for(int i=1;i<=columns;++i) {
            text+="<"+metaData.getColumnName(i)+">";
            text+=rs.getString(i);
             text+="</"+metaData.getColumnName(i)+">";
             text+="n";
         }
         text+="n";
      }

      System.out.println(text);

   }

}

Listing 6

Figure 9

Conclusion

In this article, you covered the basic concepts involved with connecting to a database from a Java application using JDBC. Incorporating a database into an application greatly expands your development options. Although this is a series of articles on object technologies, you may have noticed that you used a relational database, Microsoft Access. You will explore this issue in more detail next month. Also, as already noted, JDBC can be used in conjunction with any number of databases as long as you have the appropriate driver installed on your system.

Next month, you will write a complete Java application that will connect to the database and use various SQL commands to utilize the database, such as creating tables, updating records, and so forth. After implementing next month's example, you will be able to create a complete database application using Java and JDBC.

References

Gilbert, Stephen, and Bill McCarty: Object-Oriented Design in Java. The Waite Group, 1998.

Meyers, Scott: Effective C++. Addison-Wesley, 1992.

Tyma, Paul, Gabriel Torok and Troy Downing: Java Primer Plus. The Waite Group, 1996.

Ambler, Scott: The Object Primer. Cambridge University Press, 1998.

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 its 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.





Page 3 of 3



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel