Java Reference
In-Depth Information
Let's look at an example that uses a Statement object to add data to our
movies database. I wanted to make this example object oriented, so the first
step I took was to write a class named Movie that represented a movie. This
class is available on the Web site. The Movie class has fields to represent the
title of the movie, the category (drama, comedy, kids, and so on), the format
available, and a unique number for inventory purposes.
Be sure to view the Movie class from the topic's Web site. You will notice
that the Movie class does not contain any database programming. This
was a design decision. I wanted the Movie class to be able to be used in
many different situations, not just representing data in a database. I wrote
a separate class, MovieDatabase, that contains the database code for
performing operations on the Movies table of the movies.mdb database
using the Movie class.
The following MovieDatabase class contains an addMovie() method that
adds an entry in the Movies table of a database. Study the class carefully and
then try to determine what the code is doing:
import java.sql.*;
public class MovieDatabase
{
private Connection connection;
public MovieDatabase(Connection connection)
{
this.connection = connection;
}
public void addMovie(Movie movie)
{
System.out.println(“Adding movie: “ + movie.toString());
try
{
Statement addMovie = connection.createStatement();
String sql = “INSERT INTO Movies VALUES(“
+ movie.getNumber() + “, “
+ “'“ + movie.getMovieTitle() + “', “
+ “'“ + movie.getCategory() + “', “
+ “'“ + movie.getFormat() + “')”;
System.out.println(“Executing statement: “ + sql);
addMovie.executeUpdate(sql);
addMovie.close();
System.out.println(“Movie added successfully!”);
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}
Search WWH ::




Custom Search