Download Lab_11_Student_Handout

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CSCE156
Spring 2004
Lab 11 – JDBC Lab
Student Handout
1. Lab Objectives
Following the lab you should be able to:
 Access an SQL-based database dynamically using JDBC.
 Perform queries on an SQL-based database JDBC to retrieve items stored in the database.
 Modify and update an SQL-based database using JDBC.
2. Prior to the laboratory
 Review the laboratory handout.
 Visit the links below:
1. Review the following sections of the article “An Introduction to Basic JDBC”
http://supportweb.cs.bham.ac.uk/documentation/tutorials/docsystem/build/tutorials/jdbc/jdbc.
html :
 Basic JDBC
o Packages
o Drivers
o Getting a Connection
o Using Statements
o Working with ResultSets
o Prepared Statements
2. Review the following sections of the article “JDBC”
http://www.javajunkies.org/index.pl?lastnode_id=1025&node_id=1002 :
 What is JDBC?
 How does JDBC work?
 How do I use JDBC?
 Statements
 ResultSet
[Note: Both the tutorials given above use Microsoft Access Database and JDBC-ODBC drivers to
handle a database. However, in this lab we will only use a MySQL database and the MySQL
Connector/J driver. Except for this driver part, both types of database manipulations using
JDBC are similar.]
 Take the lab pretest.
3. Topics
Topic
Accessing a database using JDBC
Searching a database using JDBC
Dynamically storing and manipulating items stored in a database using JDBC
4. Activities/Exercises
1. Accessing a MySQL database using JDBC.
2. Searching a database using JDBC.
3. Displaying the query result in a JTable using JDBC and Swing.
4. [Extra Credit] Writing a Java program using JDBC from scratch.
Date:5/4/2017
1
CSCE156
Spring 2004
Activity 0: Getting the files and setting up the database
 Download the file Lab11Files.tar.gz from the course website into your Z:/ drive.
 Extract the files into Z:/ drive. If you download the file to the Z:/ drive, you can extract the files
using:
gunzip Lab11Files.tar.gz
tar xvf Lab11Files.tar
 All files you need for the lab should be present.
 Change the file permission of all the files as usual.
 Edit the file AlbumDB.sql, replacing insertYourAccountHere with your MySQL account name.
 Run the following command, which will replace the tables in your copy of the Albums database with
new ones that have more data.
mysql –u<yourdatabsename> -p < AlbumDB.sql
 Enter your password. This will delete all of the data in your copy of the Albums database, so save
that data if you want it.
Fig: The ER-Diagram of the Album database

Make sure that the JAR file [mysql-connector-java-3.0.11-stable-bin.jar] is in your Z:/ drive. This is
the MySQL Connector/J driver used to handle MySQL database using JDBC. You need to set the
class-path to this JAR file so that the JVM can locate it while running the program. To set the classpath run the following two commands on the command prompt:
setenv CLASSPATH . (Press Enter)
setenv CLASSPATH mysql-connector-java-3.0.11-stable-bin.jar:$CLASSPATH (Press
Enter)
[Note: There is a “.” after the first line which a part of the command, don’t miss that.]
 To check whether the class-path is set properly or not run the following command on the prompt:
echo $CLASSPATH
It should display the following line:
mysql-connector-java-3.0.11-stable-bin.jar:.
If it is not, then you must have done some mistake. Repeat the steps of the previous point to set the
class-path.
 Note: The class-path is set for this session only and it is temporary. If you close the command
prompt the class-path setting gets destroyed. So set the class-path every time you open a new
Date:5/4/2017
2
CSCE156
Spring 2004
command prompt, or else the JVM cannot locate the MySQL-JDBC driver which is in your Z:/
drive.
Activity 1: Accessing a MySQL database using JDBC
 The JDBCExample.java file demonstrates how to connect to a MySQL database, retrieve data from
the database and display it using JDBC.
 The Database.Properties file contains all the database properties.
 Open the Database.Properties file with a text editor and make the following changes:
o Change the <databasename> to your MySQL database name.
o Change the <username> to your MySQL username.
o Change the <password> to your MySQL password.
 Open the JDBCExample.java file with a text editor. Study the JDBCExample.java file carefully.
In particular, note the following:
o How the Database properties are loaded from the Database.Properties file:
Properties props = new Properties() ;
FileInputStream in = new FileInputStream("Database.Properties") ;
props.load(in) ;
o How the JDBC driver is loaded:
String drivers = props.getProperty("jdbc.drivers") ;
Class.forName(drivers) ;
o How to establish a database connection:
String database = props.getProperty("database. name")
con = DriverManager.getConnection(database,user,passwd);
o How to check whether or not the database connection could be properly established:
if(!con.isClosed())
System.out.println("Successfully connected to MySQL server...");
o How to create a statement object:
stmt=con.createStatement() ;
o How to execute a simple query and store the retrieved result in a ResultSet
ResultSet rs = stmt.executeQuery("SELECT * FROM Albums");
o How to close the ResultSet:
rs.close() ;
o How to close an open statement:
stmt.close() ;
o How the connection to the MySQL database is closed inside the finally block:
finally {
try {
if(con != null)
con.close();
} catch(SQLException e) {}
}
 Note that since the program is actually a Java program, the entire code is written within a try block
and the exception handling is done within the catch block.
 Now that you have seen how to perform queries on a MySQL database using JDBC, modify the
JDBCExample.java file so that it updates the Album database by inserting a new musician whose
first name is “XX”, last name is “YY” and who is from country “CC”.
Date:5/4/2017
3
CSCE156
Spring 2004
 If you are not sure how to do this, review the article “An Introduction to Basic JDBC” (see Section 2
of this Lab), specifically the “1.6. Prepared Statements” section in the article.
 Answer Questions 1 and 2 on the worksheet for Activity 1 after you are done.
Activity 2: Searching a database using JDBC
 In this activity you are given a Java program that accepts a string as input from the command line.
You are required to use JDBC to search the database for all the albums containing that string in their
titles.
 Open the AlbumSearch.java file with a text editor and see what it does. It accepts a string from the
command line.
 Carry out the following modifications:
o Modify the AlbumSearch.java to access the AlbumDB database.
o Next write JDBC code to execute the appropriate query on the database to search for the
string entered by the user, inside the album titles.
o Display the album titles returned by the query on the command prompt.
o You may want to be able to run the search query over and over again in order to search for
different words. So, in order to write the search query using JDBC, use a PreparedStatement
object instead of a Statement object.
 Demonstrate your modified AlbumSearch.java to the Lab instructor by searching for words “love”
and “Kid” inside album titles.
Activity 3: Displaying the query result in a JTable using JDBC and Swing
 Note: For this activity you need to use NetBeans IDE. (Start -> Program -> NetBeans IDE)
 The SimpleDBTable.java program uses both JDBC and Java Swing component (JTable) to display
the contents of the database in a tabular form.
 Open the SimpleDBTable.java file with the NetBeans IDE.
 Study the program carefully to identify the differences between this program and the
JDBCExample.java program.
o Note that the JDBC portion (getting connection, executing query, etc.) is the same in both
programs.
o The difference is in the way we render the database information. Here we use a JTable
(Swing component) to display the database table information.
o It should display the “Bands” table in a tabular form.
 You need not study in details how the Swing components are used, if you are not familiar with
Swing.
 Compile the code using NetBeans IDE from Build -> Compile menu.
 Run the program using Build -> Execute menu.
o It should display the “Bands” table in a tabular form.
 Modify the program so that it will display the results of Activity 2 in a JTable instead of displaying
them at the command prompt.
 Note: To give command line arguments in NetBeans IDE go to Build -> Set Arguments menu and
set the argument inside the textbox.
 Demonstrate your modified SimpleDBTable.java to the TA.
Activity 4: [Extra Credit] Writing a Java program using JDBC from scratch
Date:5/4/2017
4
CSCE156
Spring 2004
 In this activity, you are required to write a Java program from scratch. The program will use JDBC
to connect to the AlbumDB database and then perform queries on the database. You may refer to the
program in Activity 1 to do this.
 Insert into the AlbumDB database the Album “METAMORPHOSIS” by Hilary Duff. Write
appropriate queries so that both the Album and the singer are entered properly into tables and
associated with one another.
 Name your program file JDBC.java.
 Demonstrate to the TA your modified JDBC.java by selecting the artist of the album
“METAMORPHOSIS”. Your query should return Hilary Duff.
[Hello Chuck, I don’t like this Extra Credit stuff. Too similar. What about writing a java program that will
sort all Albums based on a “Key” provided at the command line when running the program. For example, if
the “Key” is “Title”, then we sort by Titles. And the program will output in a JTable the albums. If the
“Key” is “Band”, etc… So, we need to give them a list of possible Keys, though.]
5. Think About
 Why do we need different drivers to connect to databases of different types?
 What is the difference between the Statement and PreparedStatement objects?
 Is the ResultSet object is necessary for all queries?
 Is using Swing the only way to display database results graphically using Java?
 What are the advantages of using JDBC in terms of building a program with a 3-tier architecture
(GUI frontend, middleware, and database backend)?
Date:5/4/2017
5