Java Reference
In-Depth Information
Because the class uses prepared statements, the PreparedStatement objects only
need to be created once, so I did this in the constructor. Study the class carefully
to see how the statements are prepared and executed.
import java.sql.*;
public class MovieDatabase
{
private Connection connection;
private PreparedStatement findByNumber, updateCategory;
public MovieDatabase(Connection connection) throws SQLException
{
this.connection = connection;
findByNumber = connection.prepareStatement(
“SELECT * FROM Movies WHERE number = ?”);
updateCategory = connection.prepareStatement(
“UPDATE Movies SET category = ? WHERE number = ?”);
}
public void changeCategory(int number, String newCategory)
{
try
{
updateCategory.setString(1, newCategory);
updateCategory.setInt(2, number);
updateCategory.executeUpdate();
System.out.println(“Verifying change...”);
findByNumber.setInt(1, number);
ResultSet results = findByNumber.executeQuery();
if(results.next())
{
System.out.println(“Category of “
+ results.getString(“title”) + “ is “
+ results.getString(“category”));
}
else
{
System.out.println(“No movie found matching number “
+ number);
}
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}
The following UpdateCategory program inputs a movie number and cate-
gory, then changes the category of the given movie. Study the program along
with the MovieDatabase class and try to determine what the output is and
what changes occur in the database.
Search WWH ::




Custom Search