Web host reseller - Hello World 69 Hello hello = new Hello();
Hello World 69 Hello hello = new Hello(); hello.connectToDB(); hello.executeSQL(); } } Listing 5.1 Hello World. (continued) Since this is our first code for connecting Java to MySQL through Connector/J, we want to spend a fair amount of time going through it. First, note that this is a traditional Java application that instantiates an object and calls a few methods. When the Hello object is instantiated, the constructor is called to handle any initialization that needs to take place. Loading the Connector/J Driver In the constructor, we have placed code that attempts to locate and instantiate our Connector/J JDBC driver. The process begins with the Class.forName method. This method is designed to dynamically load a Java class at runtime. The Java Virtual Machine (JVM) uses the current system classpath (as well as any additional paths defined when the JVM was executed) to find the class passed to the method as a parameter. In our case, the system attempts to find the Driver class found in the com.mysql.jdbc package. In Chapter 4, we placed the Connector/J JAR file in the classpath of the JVM so it could be found. Once it finds the file, the code executes the newInstance() method to instantiate a new object from the Driver class. During the instantiation, the Driver will register itself with a static class called DriverManager, which is responsible for managing all JDBC drivers installed on the current system. If the JVM is unable to locate the driver, it outputs a message to the console and exits the application. Note that the DriverManager is designed to handle multiple JDBC driver objects just as long as they register with the class. This means that you can write a Java application that connects with more than one type of database system through JDBC. Note that simply loading the JDBC driver for a database doesn t result in any type of connection with the database. Using DriverManager to Connect to a Database Once our application object has been created and initialized, the code attempts to build a connection to the database. This is an important step, and therefore we ll spend some time discussing the connection code. If you look in the
Note: If you are looking for inexpensive but high quality provider to host and run your serlvet application check Astra servlet hosting services