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 a MySQL database dynamically using JDBC.
 Perform queries on a MySQL database JDBC to retrieve items stored in the database.
 Modify and update a MySQL 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 of the tutorials given above uses Microsoft Access Database and JDBC-ODBC driver to
handle database. But in the lab we will be using MySQL database and MySQL Connector/J
driver. Except 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:4/29/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:4/29/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:4/29/2017
3
CSCE156
Spring 2004
 If you are not sure how to do this, review the first link provided in the prior to lab section again and
check the section “1.6. Prepared Statements” inside that.
 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 write JDBC code in order to search the database to determine all the albums
present in the database containing that word.
 Open the AlbumSearch.java file with a text editor and see what it does. It accepts a string from the
command line.
 Modifications to be done:
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 PreparedStatement
object instead of 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 notice the difference between this program and the
JDBCExample.java program.
 As you could notice the JDBC part (getting connection, executing query etc.) is same as that of the
other program.
 The difference is in the way we render the database information. Here we are using a JTable (Swing
component) to display the database table information.
 You need not study details about Swing components used, if you are not very familiar with Swing.
 Now compile the code using NetBeans IDE from Build -> Compile menu.
 Then run the program using Build -> Execute menu.
 It should display the “Bands” table in a tabular form.
 Now 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
 In this activity, you are required to write a Java program from scratch that uses 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.
Date:4/29/2017
4
CSCE156
Spring 2004
 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.
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 use of Swing the only way to display database results graphically using Java?
 Is the use of the intermediary vector in Activity 3 for storing row-data and column names
mandatory?
Date:4/29/2017
5