Java Reference
In-Depth Information
PreparedStatement
Define a dynamic SQL statement.
CallableStatement
Execute stored procedures in the database.
ResultSet
Provide a JDBC cursor mechanism.
In the next exercise, you see how these classes can be used to access data from a MySQL database.
accessing a relational Database Using JDBC 
try it out
1.
Download and install the JDBC driver for MySQL. In my case (working on a Windows 8
computer), I downloaded MySQL Connector/J from http://dev.mysql.com/downloads/
connector/j/5.0.html , which is the official JDBC type 4 driver for MySQL. The file called
mysql-connector-java-5.1.30-bin.jar was then installed in my directory C:\Program Files
(x86)\MySQL\Connector J 5.1.30 . Make sure to add the directory C:\Program Files (x86)\
MySQL\Connector J 5.1.30 to the CLASSPATH environment variable. As an alternative, you could
also right-click the project in Eclipse, choose Build Path Configure Build Path Add External
JARs, and then explicitly add the file mysql-connector-java-5.1.30-bin.jar .
2.
Create a new project in Eclipse. Perhaps call it Chapter9 to keep the exercises organized according
to the chapters in this topic.
3.
Create a new class by right-clicking on the src folder in your new project. Select New Class.
4.
In the Name field, enter the name of your class, JDBCExample1 . In the bottom portion of the New
Java Class window, there is a section that reads, “Which method stubs would you like to create?”
You may choose to check the box next to “public static void main(String[] args)” to automatically
create a main method.
5.
You should automatically have the basis for the class body shown here:
public class JDBCExample1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
6.
Adapt this class definition as follows:
import java.sql.*;
public class JDBCExample1 {
public static void main(String[] args) {
try {
System.out.println("Loading JDBC driver...");
Class.forName("com.mysql.jdbc.Driver");
System.out.println("JDBC driver successfully loaded!");
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
Search WWH ::




Custom Search