Java Programming Chapter 21 How to use JDBC to work with a d
Java Programming
Chapter 21: How to use JDBC to work with a database
1. A type-1 driver uses ________________ to connect to almost any type of database.
2. To disconnect a Java application from a Derby database, you run the _________________________ method with a parameter that indicates that one or all databases should be shut down.
3. You use the __________________ class to work with data returned from a SQL query.
4. Because the database server can cache and reuse ___________________ statements, they are more efficient than regular statements.
5. Write code that executes the following SELECT statement:
SELECT Title, Year
FROM Movies
WHERE DIRECTOR = 37
ORDER BY Year DESC
You may assume that a connection to the database has already been established and is stored in a Connection object named dbcon. Store the result set in a variable named result. (You must declare the result variable, but don’t worry about catching exceptions.)
6. Assume that a ResultSet object named result contains the results of the following query:
SELECT Title, Year
FROM Movies
WHERE Director = 37
ORDER BY Year DESC
Assuming that the Title and Year columns store string data, write code that prints the title and year for each row in the result set to the console. The output should look like this:
The Birds (1963)
Psycho (1960)
North By Northwest (1959)
Solution
 1)   JDBC calls into ODBC calls and sends them to the ODBC driver
 2)   DriverManager.getConnection(\"jdbc:derby:;shutdown=true\");
5) ************ ans********
conn = DriverManager.getConnection(DB_URL, USER, PASS);
 // jdbc driver username and passwords as parameters
   
   
 //Executing a query
 //Creating statement
 stat = conn.createStatement();
String sql = \"SELECT Title, Year, FROM Movies WHERE DIRECTOR=37 ORDER BY Year DESC\";
 ResultSet rs = stat.executeQuery(sql);
 //STEP 5: Extract data from result set
 while(rs.next()){
 //Retrieve information
 String first = rs.getString(\"title\");
 String last = rs.getString(\"year\");
//Display values
 System.out.print(\", Title \" + title);
 System.out.println(\",year: \" + last);
 }
 rs.close(); // closing


