Most Sample Code from "Java How to Program, Sixth Edition" from Deitel and Deitel
For more on Eclipse see:
Eclipse offers such things as:
For more on Netbeans see:
For the slides created by Sean, click here:
For the promo on Matisse (a new way of setting up GUI interfaces) see:
http://www.netbeans.org/kb/41/flash-matisse.html
Netbeans offers:
You first have to have a database created for you on hercules:
.....Wait 15 minutes before trying to access your database
Before you start playing with SQL, you can get the following file:
Original | Modified |
---|---|
books.orig | books.sql |
(you want the Modified version, but the original is left in case you want to play with SQL on your own MySQL server)
Now, you can start playing with sql. You will first have to be on hercules:
ssh hercules
The relevant command for mysql is:
mysql -p username
It should ask you for your sql password (the one that you chose above). If all is well, you will get an sql prompt.
The following table (from page 1197 of Deitel) summarizes some SQL query keywords:
SQL keyword | Description |
---|---|
SELECT | Retrieves data from one or more tables |
FROM | Tables involved in the query. Required in every SELECT. |
WHERE | Criteria for selection that determine the rows to be retrieved, deleted or updated. Optional in a SQL query or a SQL statement |
GROUP BY | Criteria for grouping rows. Optional in a SELECT query. |
ORDER BY | Criteria for ordering rows. Optional in a SELECT query. |
INNER JOIN | Merge rows from multiple tables |
INSERT | Insert rows into a specified table |
UPDATE | Update rows in a specified table |
DELETE | Delete rows from a specified table |
We will walk through examples of using each of these using the book.sql database. These examples are taken from Deitel's book.
Let's get started. First let's see what you've got in your database:
show tables;
Nothing eh? Well, let's load up the books.sql database which is going load up four tables:
source books.sql
Now, you should have four tables. If we want to show all columns from the authors table, we can type:
select * from authors;
For only certain columns, we can type:
select authorID, lastName from authors;
Let's get a subset of the database using "where":
select title, editionNumber, copyright
from titles
where copyright > 2002;
Where clause can contain the operators: <, >, <=, >=, =, <> and LIKE. Like is used for pattern matching with wildcard characters percent (%) and under
score (_). The below pattern searches for authors whose last name starts with D. The % indicates any number of characters (including zero) can appear after the D.
select authorID, firstName, lastName
from authors
where lastName like 'D%';
The below example locates authors whose last names start with any character (specified by _), followed by the letter i, followed by any number of additional characters (specified by %)
select authorID, firstName, lastName
from authors
where lastName like '_i%';
The following displays the authors table in ascending order based on the last name. The order can be either ASC (ascending) or DESC (descending). If you do not specify an order, then ASC is used.
select authorID, firstName, lastName
from authors
order by lastName ASC;
The following shows ordering in ascending order based on lastName then firstName:
select authorId, firstName, lastName
from authors
order by lastName, firstName;
If we want to sort in descending order for both fields, how would we do it?
The following shows a combination of "where" and "order by":
select isbn, title, editionNumber, copyright, price
from titles
where title like '%How to Program'
order by title;
The following shows a join of two tables:
select firstName, lastName, isbn
from authors
inner join authorISBN on authors.authorID = authorISBN.authorID
order by lastName, firstName;
Can we do this in another way?
The following inserts a new record into the authors table:
insert into authors (firstName, lastName)
values ('Sue', 'Smith');
The following shows updating Sue's record so that her last name is now "Jones"
update authors
set lastName = 'Jones'
where lastName = 'Smith' and firstName = 'Sue';
Instead of using where lastName='Smith' and firstName = 'Sue', is there anything else we could have typed?
The following demonstrates how to remove Sue from the authors table:
delete from authors
where authorID=5;
*Bonus* The following command is useful for finding out information about column headers and what kind of data is in each field (or column) of the specified table.
describe authors;
Note: in order to run these programs, you must be on hercules and have loaded books.sql into mysql. See the above section for a description on how to do this.
The following code connects to your database and displays the contents of the authors table
Original | Modified |
---|---|
DisplayAuthors.orig | DisplayAuthors.java |
You will have to modify two lines to get this working:
static final String DATABASE_URL="jdbc:mysql://localhost/nova";
to:
static final String DATABASE_URL="jdbc:mysql://localhost/your_userID";
connection=DriverManager.getConnection(DATABASE_URL,"nova", "blah");
to
connection=DriverManager.getConnection(DATABASE_URL,"your_userID", "your_sql_password");
A couple of comments on this code:
lib\ext
directory so that you can use it.Class.forName
to load the database driver. You must do this before connecting to the database.Connection
objects enable programs to create SQL statements that access databases.connection=DriverManager.getConnection(DATABASE_URL,"your_userID", "your_sql_password")
sets up the connection to the Database using the userID and password specified as the second and third arguments.jdbc:mysql://localhost/nova
, specifies the protocol for communication (jdbc
), the subprotocol for communication (mysql
), and the location of the database (//localhost/nova
--where localhost
is the name of the MySQL server host and nova
is the name of the database) Statement
objects are used to submit SQL to the database. Notice you use the connection
to createStatement
.statement.executeQuery()
executes the specified query and returns the results to resultSet
.resultSet
, the data is extracted in the following manner:
metaData
from the resultSet
. The metaData
contains information such as the number of columns, the column names and types. Use the metaData
to get
metaData.getColumnCount()
metaData.getColumnName(i)
//notice that the columns start at i=1 resultSet.next()
//moves the cursor to the next row resultSet.getObject(i)
//notice the columns start at i=1finally
block closes the Statement
and database Connection
This next code allows the user to enter their own query:
Original | Modified |
---|---|
ResultSetTableModel.orig | ResultSetTableModel.java |
DisplayQueryResults.orig | DisplayQueryResults.java |
Once again, to get this code working you will have to modify the following lines of code in DisplayQueryResults.java:
static final String DATABASE_URL = "jdbc:mysql://localhost/nova"; static final String USERNAME="nova"; static final String PASSWORD="blah";
Change it to your username and password.
The purpose of DisplayQueryResults.java
is to produce the GUI interface. Notice that you are using BorderLayout and the the "NORTH" has a TextArea and Submit button. The "CENTER" has the resultTable
that contains the results of the query to your database in tabular format.
When you click on the "Submit Query" button, the table is adjusted according to the query in the textarea. The code in DisplayQueryResults.java
that initiates this is:
tableModel.setQuery(queryArea.getText());
We haven't talked about ResultSetTableModel.java
. This is the code that performs the connection to the database and maintains the ResultSet. The magic in how the table is updated has to do with the fact that ResultSetTableModel
extends class AbstractTableModel
, which implements interface TableModel
. ResultSetTableModel
overrides TableModel
methods:
getColumnClass
getColumnCount
getColumnName
getRowCount
getValueAt
These are the functions that are behind the magic of displaying a new Table based on the current query.
Notice that the ResultSetTableModel
constructor accepts five arguments--the driver class name, the URL of the database, the username, the password and the default query to perform.
The constructor for the ResultSetTableModel completes the following steps:
connection
statement
based on the connection
. Notice that there is a different version of the method
createStatement
; it takes two arguments--the result set type and the result set concurrency. The result set type specifies whether the ResultSet
's cursor is able to scroll in both directions or forward only and whether the ResultSet
is sensitive to changes. The result set concurrency specifies whether the ResultSet
can be updated with ResultSet
's update methods. With the arguments in this example, ResultSet
is scrollable, insensitive to changes and read only. (page 1217, Deitel) ResultSetTableModel
's method setQuery
, which performs the default query. A couple of things to note:
JTable
row and column numbers are counted from 0, but ResultSet
row and column numbers are counted from 1.ResultSetTableMode
l's getValueAt method uses ResultSet method absolute
to position the ResultSet cursor at a specific row fireTableStructureChange
causes the JTable
to repopulate its rows and columns with the new ResultSet dataThe next example shows a method of querying databases without using Connections and Statements. You use a RowSet
instead. This example performs the same action as the DisplayAuthors.java
Original | Modified |
---|---|
JdbcRowSetTest.orig | JdbcRowSetTest.java |
Again, you will have to modify the code to contain your own database, username and password
You can note the following:
set
methods that specify things such as the database URL, the username and password.JdbcRowSet
method setCommand
is used to specify the SQL queryJdbcRowSet
method execute
executes the query; it performs four actions--it establishes a Connection
, prepares the query Statement
, executes the query and stores the ResultSet
returned by query. The Connection
, Statement
and ResultSet
are encapsulated in the JdbcRowSet
object. (page 1227, Deitel)
The following are a couple of recommended links on sql:
You also have access to Oracle on hercules. Try:
sqlplus /
To get MySQL working on your home computer, you need two things (from www.mysql.com):
The tricky part about the driver is connecting it to the classpath. When you download the connector, there are two .jar files. The important one is:
mysql-connector-java-3.1.10-bin.jar
If you do not add this .jar file to the classpath, then a "java.lang.ClassNotFoundException " will be thrown. You have two solutions:
java -classpath C:\mysql-connector-java-3.1.10\mysql-connector-java-3.1.10-bin.jar;. DisplayAuthors
Note: don't forget the ";." this indicates the current directory. Without it, DisplayAuthors will not be found. The above is specific to Windows. On Unix, you use a full colon ":" instead of a semi-colon ";"
mysql-connector-java-3.1.10-bin.jar
file to the JRE's lib\ext
directory