Χειμερινό εξάμηνο Πέτρος Κωμοδρόμος. eng.ucy.ac.cy/petros

Σχετικά έγγραφα
Εργαστήριο Ανάπτυξης Εφαρμογών Βάσεων Δεδομένων. Εξάμηνο 7 ο

Προγραμματισμός ΙΙ (Java) 6. Διαχείριση δεδομένων

Εργαστήριο Ανάπτυξης Εφαρμογών Βάσεων Δεδομένων. Εξάμηνο 7 ο

Εργαστήριο Ανάπτυξης Εφαρμογών Βάσεων Δεδομένων. Εξάμηνο 7 ο

MySQL + Γλώσσα Προγραμματισμού. Βάσεις Δεδομένων Ευαγγελία Πιτουρά 1

Instruction Execution Times

ΠΑΝΕΠΙΣΤΗΜΙΟ ΚΥΠΡΟΥ - ΤΜΗΜΑ ΠΛΗΡΟΦΟΡΙΚΗΣ ΕΠΛ 133: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΕΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ ΕΡΓΑΣΤΗΡΙΟ 3 Javadoc Tutorial

MySQL + Γλώσσα Προγραμματισμού. Βάσεις Δεδομένων Ευαγγελία Πιτουρά 1

(C) 2010 Pearson Education, Inc. All rights reserved.

Δομές Δεδομένων - Εργαστήριο 2. Λίστες

CYTA Cloud Server Set Up Instructions

Αντικειμενοστρεφής Προγραμματισμός

Στο εστιατόριο «ToDokimasesPrinToBgaleisStonKosmo?» έξω από τους δακτυλίους του Κρόνου, οι παραγγελίες γίνονται ηλεκτρονικά.

Εγκατάσταση λογισμικού και αναβάθμιση συσκευής Device software installation and software upgrade

ΓΡΑΜΜΙΚΟΣ & ΔΙΚΤΥΑΚΟΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ

SOAP API. Table of Contents

Δημιουργία Λογαριασμού Διαχείρισης Business Telephony Create a Management Account for Business Telephony

department listing department name αχχουντσ ϕανε βαλικτ δδσϕηασδδη σδηφγ ασκϕηλκ τεχηνιχαλ αλαν ϕουν διξ τεχηνιχαλ ϕοην µαριανι

EPL 603 TOPICS IN SOFTWARE ENGINEERING. Lab 5: Component Adaptation Environment (COPE)

ΠΑΝΔΠΙΣΗΜΙΟ ΜΑΚΔΓΟΝΙΑ ΠΡΟΓΡΑΜΜΑ ΜΔΣΑΠΣΤΥΙΑΚΧΝ ΠΟΤΓΧΝ ΣΜΗΜΑΣΟ ΔΦΑΡΜΟΜΔΝΗ ΠΛΗΡΟΦΟΡΙΚΗ

PortSip Softphone. Ελληνικά Ι English 1/20

The Simply Typed Lambda Calculus

Homework 3 Solutions

. Εργαστήριο Βάσεων Δεδομένων. Triggers

ΚΥΠΡΙΑΚΗ ΕΤΑΙΡΕΙΑ ΠΛΗΡΟΦΟΡΙΚΗΣ CYPRUS COMPUTER SOCIETY ΠΑΓΚΥΠΡΙΟΣ ΜΑΘΗΤΙΚΟΣ ΔΙΑΓΩΝΙΣΜΟΣ ΠΛΗΡΟΦΟΡΙΚΗΣ 19/5/2007

Physical DB Design. B-Trees Index files can become quite large for large main files Indices on index files are possible.

Οδηγίες Αγοράς Ηλεκτρονικού Βιβλίου Instructions for Buying an ebook

Test Data Management in Practice

Dynamic types, Lambda calculus machines Section and Practice Problems Apr 21 22, 2016

EE512: Error Control Coding

Modbus basic setup notes for IO-Link AL1xxx Master Block

Αντικειμενοστρεφής Προγραμματισμός

ΚΥΠΡΙΑΚΟΣ ΣΥΝΔΕΣΜΟΣ ΠΛΗΡΟΦΟΡΙΚΗΣ CYPRUS COMPUTER SOCIETY 21 ος ΠΑΓΚΥΠΡΙΟΣ ΜΑΘΗΤΙΚΟΣ ΔΙΑΓΩΝΙΣΜΟΣ ΠΛΗΡΟΦΟΡΙΚΗΣ Δεύτερος Γύρος - 30 Μαρτίου 2011

ΠΑΝΕΠΙΣΤΗΜΙΟ ΠΕΙΡΑΙΩΣ ΤΜΗΜΑ ΠΛΗΡΟΦΟΡΙΚΗΣ. Βάσεις Δεδομένων (4 ο εξάμηνο) Εργαστήριο MySQL #2

ΤΕΧΝΟΛΟΓΙΚΟ ΠΑΝΕΠΙΣΤΗΜΙΟ ΚΥΠΡΟΥ ΤΜΗΜΑ ΝΟΣΗΛΕΥΤΙΚΗΣ

Special edition of the Technical Chamber of Greece on Video Conference Services on the Internet, 2000 NUTWBCAM

Block Ciphers Modes. Ramki Thurimella

SPEEDO AQUABEAT. Specially Designed for Aquatic Athletes and Active People

Αποτελεί ισχυρό εργαλείο, µε υψηλή απόδοση & αποτελεσµατικότητα.

ιαδικτυακές Εφαρµογές

Approximation of distance between locations on earth given by latitude and longitude

ΚΥΠΡΙΑΚΗ ΕΤΑΙΡΕΙΑ ΠΛΗΡΟΦΟΡΙΚΗΣ CYPRUS COMPUTER SOCIETY ΠΑΓΚΥΠΡΙΟΣ ΜΑΘΗΤΙΚΟΣ ΔΙΑΓΩΝΙΣΜΟΣ ΠΛΗΡΟΦΟΡΙΚΗΣ 11/3/2006

Συστήματα Διαχείρισης Βάσεων Δεδομένων

Other Test Constructions: Likelihood Ratio & Bayes Tests

5. Ανασκόπηση αντικειμενοστραφούς προγραμματισμού

2 Composition. Invertible Mappings

Αποθηκευμένες Διαδικασίες Stored Routines (Procedures & Functions)

derivation of the Laplacian from rectangular to spherical coordinates

10 η Διάλεξη Python Βάσεις δεδομένων στη python

Phys460.nb Solution for the t-dependent Schrodinger s equation How did we find the solution? (not required)

, Evaluation of a library against injection attacks

ΚΥΠΡΙΑΚΗ ΕΤΑΙΡΕΙΑ ΠΛΗΡΟΦΟΡΙΚΗΣ CYPRUS COMPUTER SOCIETY ΠΑΓΚΥΠΡΙΟΣ ΜΑΘΗΤΙΚΟΣ ΔΙΑΓΩΝΙΣΜΟΣ ΠΛΗΡΟΦΟΡΙΚΗΣ 24/3/2007

ΚΕΡΑΜΟΠΟΥΛΟΣ ΕΥΚΛΕΙΔΗΣ

Ψηφιακή ανάπτυξη. Course Unit #1 : Κατανοώντας τις βασικές σύγχρονες ψηφιακές αρχές Thematic Unit #1 : Τεχνολογίες Web και CMS

Business English. Ενότητα # 9: Financial Planning. Ευαγγελία Κουτσογιάννη Τμήμα Διοίκησης Επιχειρήσεων

Πρόβλημα 1: Αναζήτηση Ελάχιστης/Μέγιστης Τιμής

CHAPTER 25 SOLVING EQUATIONS BY ITERATIVE METHODS

TMA4115 Matematikk 3

Αντικειμενοστρεφής Προγραμματισμός

VBA ΣΤΟ WORD. 1. Συχνά, όταν ήθελα να δώσω ένα φυλλάδιο εργασίας με ασκήσεις στους μαθητές έκανα το εξής: Version ΗΜΙΤΕΛΗΣ!!!!

Démographie spatiale/spatial Demography

Ψηφιακή ανάπτυξη. Course Unit #1 : Κατανοώντας τις βασικές σύγχρονες ψηφιακές αρχές Thematic Unit #1 : Τεχνολογίες Web και CMS

TaxiCounter Android App. Περδίκης Ανδρέας ME10069

Μορφοποίηση υπό όρους : Μορφή > Μορφοποίηση υπό όρους/γραμμές δεδομένων/μορφοποίηση μόο των κελιών που περιέχουν/

How to register an account with the Hellenic Community of Sheffield.

Partial Trace and Partial Transpose

Assalamu `alaikum wr. wb.

HOMEWORK 4 = G. In order to plot the stress versus the stretch we define a normalized stretch:

Εργαστήριο 9. Styling with Javascript

C.S. 430 Assignment 6, Sample Solutions

Galatia SIL Keyboard Information

Main source: "Discrete-time systems and computer control" by Α. ΣΚΟΔΡΑΣ ΨΗΦΙΑΚΟΣ ΕΛΕΓΧΟΣ ΔΙΑΛΕΞΗ 4 ΔΙΑΦΑΝΕΙΑ 1

Web Data Mining ΕΡΓΑΣΤΗΡΙΟ 2 & 3. Prepared by Costantinos Costa Edited by George Nikolaides. EPL Data Mining on the Web

Example Sheet 3 Solutions

ΠΤΥΧΙΑΚΗ ΕΡΓΑΣΙΑ "ΠΟΛΥΚΡΙΤΗΡΙΑ ΣΥΣΤΗΜΑΤΑ ΛΗΨΗΣ ΑΠΟΦΑΣΕΩΝ. Η ΠΕΡΙΠΤΩΣΗ ΤΗΣ ΕΠΙΛΟΓΗΣ ΑΣΦΑΛΙΣΤΗΡΙΟΥ ΣΥΜΒΟΛΑΙΟΥ ΥΓΕΙΑΣ "

UNIVERSITY OF CALIFORNIA. EECS 150 Fall ) You are implementing an 4:1 Multiplexer that has the following specifications:

Οδηγίες χρήσης. Registered. Οδηγίες ένταξης σήματος D-U-N-S Registered στην ιστοσελίδα σας και χρήσης του στην ηλεκτρονική σας επικοινωνία

Αρχές Τεχνολογίας Λογισμικού Εργαστήριο

Βασίλης Χριστοφίδης Επαναληπτική Εξέταση (3 ώρες) Ηµεροµηνία: 21 Σεπτεµβρίου 2012

ΚΥΠΡΙΑΚΗ ΕΤΑΙΡΕΙΑ ΠΛΗΡΟΦΟΡΙΚΗΣ CYPRUS COMPUTER SOCIETY ΠΑΓΚΥΠΡΙΟΣ ΜΑΘΗΤΙΚΟΣ ΔΙΑΓΩΝΙΣΜΟΣ ΠΛΗΡΟΦΟΡΙΚΗΣ 6/5/2006

the total number of electrons passing through the lamp.

Συντακτικές λειτουργίες

Διδάσκων: Παναγιώτης Ανδρέου

Math 6 SL Probability Distributions Practice Test Mark Scheme

Περιγραφή της εργασίας

Managing Information.! Lecturer: N. Kyritsis, MBA, Ph.D. Candidate Athens University of Economics and Business!!

DESIGN OF MACHINERY SOLUTION MANUAL h in h 4 0.

ΟΙΚΟΝΟΜΙΚΟ ΠΑΝΕΠΙΣΤΗΜΙΟ ΑΘΗΝΩΝ ΤΜΗΜΑ ΔΙΟΙΚΗΤΙΚΗΣ ΕΠΙΣΤΗΜΗΣ ΚΑΙ ΤΕΧΝΟΛΟΓΙΑΣ. Τεχνολογίες και Εφαρμογές Διαδικτύου. Σχεδίαση Συστήματος

Strain gauge and rosettes

Διαδίκτυο των Αντικειμένων - IoT.

Capacitors - Capacitance, Charge and Potential Difference

5.4 The Poisson Distribution.

Εργαστήριο Βάσεων Δεδομένων. Triggers

Ασφάλεια σε χώρους αναψυχής: Ένα σύστημα από έξυπνα αντικείμενα

ΚΕΡΑΜΟΠΟΥΛΟΣ ΕΥΚΛΕΙΔΗΣ

Δίκτυα Επικοινωνιών ΙΙ: OSPF Configuration

Advanced Subsidiary Unit 1: Understanding and Written Response

Τμήμα Πολιτικών και Δομικών Έργων

(Διαφάνειες Νίκου Βιδάκη)

Μηχανική Μάθηση Hypothesis Testing

Transcript:

23. Βάσεις δεδομένων (databases) και JDBC Χειμερινό εξάμηνο 2005 Πέτρος Κωμοδρόμος komodromos@ucy.ac.cy http://www. www.eng. eng.ucy.ac.cy/petros 1

Θέματα Introduction Relational Databases Relational Database Overview: The books Database SQL Basic SELECT Query WHERE Clause ORDER BY Clause Merging Data from Multiple Tables: INNER JOIN INSERT Statement UPDATE Statement DELETE Statement 2

Instructions to install MySQL and MySQL Connector/J Instructions on Setting MySQL User Account Creating Database books in MySQL Manipulating Databases with JDBC Connecting to and Querying a Database Querying the books Database Stored Procedures RowSet Interface 3

Introduction Database Collection of data DBMS SQL Database management system Storing and organizing data Relational database Structured Query Language 4

RDBMS Relational database management system MySQL JDBC o Open source o Available for both Windows and Linux o dev.mysql.com/downloads/mysql/4.0.hml Java Database Connectivity JDBC driver o Enable Java applications to connect to database o Enable programmers to manipulate databases using JDBC 5

Relational Databases Relational database Table o Rows, columns Primary key SQL queries o Unique data Specify which data to select from a table 6

Employee table sample data. 7

Result of selecting distinct Department and Location data from table Employee. 8

Relational Database Overview: The books Database Sample books database Four tables o authors authorid, firstname, lastname o publishers o titles publisherid, publishername isbn,, title, editionnumber,, copyright, publisherid, imagefile,, price o authorisbn authorid, isbn 9

authors table from books. Column authorid firstname lastname Description Author s ID number in the database. In the books database, this integer column is defined as autoincremented. For each row inserted in this table, the authorid value is increased by 1 automatically to ensure that each row has a unique authorid. This column represents the table s primary key. Author s first name (a string). Author s last name (a string). authorid firstname lastname 1 Harvey Deitel 2 Paul Deitel 3 Tem Nieto 4 Sean Santry 10

publishers table from books. Column publisherid publishername Description The publisher s ID number in the database. This autoincremented integer is the table s primary key. The name of the publisher (a string). publisherid publishername 1 Prentice Hall 2 Prentice Hall PTG 11

titles table from books. Column isbn title editionnumber copyright publisherid imagefile price Description ISBN of the book (a string). The table s primary key. ISBN is an abbreviation for International Standard Book Number a numbering scheme that publishers worldwide use to give every book a unique identification number. Title of the book (a string). Edition number of the book (an integer). Copyright year of the book (a string). Publisher s ID number (an integer). A foreign key that relates this table to the publishers table. Name of the file containing the book s cover image (a string). Suggested retail price of the book (a real number). [Note: The prices shown in Fig. 25.8 are for example purposes only.] 12

Relational Database Overview: : The books Database Foreign key A column o matches the primary key column in another table Helps maintain the Rule of Referential Integrity o Every foreign key value must appear as another table s s primary key value Entity-relationship (ER) diagram Tables in the database Relationships among tables 13

Rule of Entity Integrity Primary key uniquely identifies each row Every row must have a value for every column of the primary key Value of the primary key must be unique in the table 14

Common Programming Errors Not providing a value for every column in a primary key breaks the t Rule of Entity Integrity and causes the DBMS to report an error. Providing the same value for the primary key in multiple rows causes the DBMS to report an error. Providing a foreign-key value that does not appear as a primary-key value in another table breaks the Rule of Referential Integrity and causes s the DBMS to report an error. 15

Sample data from the titles table of books isbn title editionn umber copyright publisher ID Image File price 0131426443 C How to Program 4 2004 1 chtp4.jpg 85.00 0130384747 C++ How to Program 4 2003 1 cpphtp4.j pg 85.00 0130461342 Java Web Services for Experienced Programmers 0131483986 Java How to Program 1 2003 1 jwsfep1.j pg 54.99 6 2005 1 jhtp6.jpg 85.00 013100252X The Complete C++ Training Course 4 2003 2 cppctc4.j pg 109.99 0130895601 Advanced Java 2 Platform How to Program 1 2002 1 advjhtp1. jpg 69.95 16

authorisbn table from books. Column Description authorid isbn The author s ID number, a foreign key to the authors table. The ISBN for a book, a foreign key to the titles table. authorid isbn authorid isbn 1 0130895725 2 0139163050 2 0130895725 3 0130829293 2 0132261197 3 0130284173 2 0130895717 3 0130284181 2 0135289106 4 0130895601 17

Table relationships in books. 18

SQL keywords: SQL queries and statements SQL keyword Description SELECT FROM WHERE GROUP BY ORDER BY INNER JOIN INSERT UPDATE DELETE Retrieves data from one or more tables. Tables involved in the query. Required in every SELECT. Criteria for selection that determine the rows to be retrieved, deleted or updated. Optional in a SQL query or a SQL statement. Criteria for grouping rows. Optional in a SELECT query. Criteria for ordering rows. Optional in a SELECT query. Merge rows from multiple tables. Insert rows into a specified table. Update rows in a specified table. Delete rows from a specified table. 19

Basic SELECT Query Simplest format of a SELECT query SELECT * FROM tablename o SELECT * FROM authors Select specific fields from a table SELECT authorid, lastname FROM authors authorid lastname 1 Deitel 2 Deitel 3 Nieto 4 Santry 20

Παρατηρήσεις For most queries, the asterisk (*)( ) should not be used to specify column names. In general, programmers process results by knowing in advance the e order of the columns in the result for example selecting authorid and lastname from table authors ensures that the columns will appear in the result with authorid as the first column and lastname as the second column. Programs typically process result columns by specifying the column number in the result (starting from number 1 for the first column). Selecting columns by name also a avoids returning unneeded columns and protects against changes in the actual a order of the columns in the table(s). If a programmer assumes that the columns are always returned in the same order from a query that uses the asterisk (*), the program may process p the result incorrectly. If the column order in the table(s) ) changes or if additional columns are added at a later time, the order of the columns in the t result would change accordingly. 21

WHERE Clause specify the selection criteria SELECT columnname1, columnname2, FROM tablename WHERE criteria > SELECT title, editionnumber,, copyright FROM titleswhere copyright > 2002 title editionnumber copyright The Complete C++ Training Course 4 2003 Java How to Program 5 2003 C How to Program 4 2004 Internet and World Wide Web How to Program 3 2004 Java How to Program 6 2005 C# How to Program 1 2003 22

WHERE Clause WHERE clause condition operators <, >, <=, >=, =, <> LIKE o wildcard characters % and _ (in some systems: * and?) > SELECT authorid, firstname, lastname FROM authors WHERE lastname LIKE D% D% authorid firstname lastname 1 Harvey Deitel 2 Paul Deitel 23

WHERE Clause > SELECT authorid, firstname, lastname FROM authorswhere lastname LIKE _i% authorid firstname lastname 3 Tem Nieto 24

ORDER BY Clause Optional ORDER BY clause SELECT columnname1, columnname2, FROM tablename ORDER BY column ASC > SELECT authorid, firstname, lastname FROM authors ORDER BY lastname ASC SELECT columnname1, columnname2, FROM tablename ORDER BY column DESC > SELECT authorid, firstname, lastname FROM authors ORDER BY lastname DESC 25

authorid firstname lastname 1 Harvey Deitel 2 Paul Deitel 3 Tem Nieto 4 Sean Santry authorid firstname lastname 4 Sean Santry 3 Tem Nieto 1 Harvey Deitel 2 Paul Deitel 26

ORDER BY Clause ORDER BY multiple fields ORDER BY column1 sortingorder, column2 sortingorder, > SELECT authorid, firstname, lastname FROM authors ORDER BY lastname, firstname authorid firstname lastname 1 Harvey Deitel 2 Paul Deitel 3 Tem Nieto 4 Sean Santry 27

ORDER BY Clause Combine the WHERE and ORDER BY clauses > SELECT isbn,, title, editionnumber,, copyright, price FROM titles WHERE title LIKE %How to Program ORDER BY title ASC isbn title Edition -Number copyright price 0130895601 Advanced Java 2 Platform How to Program 1 2002 69.95 0131426443 C How to Program 4 2004 85.00 0130384747 C++ How to Program 4 2003 85.00 013028419x e-business and e-commerce How to 1 Program 2001 69.95 0131450913 Internet and World Wide Web How 3 to Program 2004 85.00 0130284181 Perl How to Program 1 2001 69.95 0134569555 Visual Basic 6 How to Program 1 1999 69.95 0130284173 XML How to Program 1 2001 69.95 28

Merging Data from Multiple Tables: INNER JOIN Split related data into separate tables Join the tables Merge data from multiple tables into a single view INNER JOIN o SELECT columnname1, columnname2, FROM table1 INNER JOIN table2 ON table1.columnname = table2.column2name o SELECT firstname, lastname, isbn FROM authors, authorisbn INNER JOIN authorisbn ON authors.authorid = authorisbn.authorid ORDER BY lastname, firstname 29

Παρατηρήσεις If a SQL statement includes columns from multiple tables that have the same name, the statement must precede those column names with their table names and a dot (e.g., authors.authorid). In a query, failure to qualify names for columns that have the same s name in two or more tables is an error. 30

Sampling of authors and ISBNs for the books they have written in ascending order by lastname and firstname. firstname lastname isbn first Name lastname isbn Harvey Deitel 0130895601 Paul Deitel 0130895717 Harvey Deitel 0130284181 Paul Deitel 0132261197 Harvey Deitel 0134569555 Paul Deitel 0130895725 Harvey Deitel 0139163050 Paul Deitel 0130829293 Harvey Deitel 0135289106 Paul Deitel 0134569555 Harvey Deitel 0130895717 Paul Deitel 0130829277 Harvey Deitel 0130284173 Tem Nieto 0130161438 Harvey Deitel 0130829293 Tem Nieto 013028419x Paul Deitel 0130852473 Sean Santry 0130895601 31

Insert a row into a table INSERT Statement INSERT INTO tablename ( columnname1,, columnnamen ) VALUES ( value1,, valuen ) > INSERT INTO authors ( firstname, lastname ) VALUES ( Sue, Smith ) authorid firstname lastname 1 Harvey Deitel 2 Paul Deitel 3 Tem Nieto 4 Sean Santry 5 Sue Smith 32

Common Programming Error SQL uses the single-quote (')( ) character as a delimiter for strings. To specify a string containing a single quote (e.g., O Malley) in a SQL statement, the string must have two single quotes in the position where the single-quote character appears in the string (e.g., 'O''Malley'). The first of the two single-quote characters acts as an escape character for the second. Not escaping single-quote characters in a string that is part of a SQL statement is a SQL syntax error. 33

UPDATE Statement Modify data in a table UPDATE tablename SET columnname1 = value1,, columnnamen = valuen WHERE criteria o UPDATE authors SET lastname = Jones WHERE lastname = Smith AND firstname = Sue authorid firstname lastname 1 Harvey Deitel 2 Paul Deitel 3 Tem Nieto 4 Sean Santry 5 Sue Jones 34

DELETE Statement Remove data from a table DELETE FROM tablename WHERE criteria o DELETE FROM authors WHERE lastname = Jones AND firstname = Sue authorid firstname lastname 1 Harvey Deitel 2 Paul Deitel 3 Tem Nieto 4 Sean Santry 35

Instructions to Install MySQL and MySQL Connector/J Install MySQL Insert CD and change directory to D:\software software\mysql\mysql- 4.0.20c-win Double click SETUP.EXE Following the instruction Install MySQL Connector/J Copy mysql-connector connector-java-3.0.14-production.zip Open mysql-connector connector-java-3.0.14-production.zip o Extract its content to the C:\ driv 36

Instructions on Setting MySQL User Account Set up a user account Start database server by executing the script C:\mysql mysql\bin\mysqld Start the MySQL monitor by executing the command C:\mysql mysql\bin> bin>mysql h localhost u u root Create an account mysql> > USE mysql; mysql> > INSERT INTO user SET Host= localhost localhost, User= jhtp6 jhtp6,, Password=PASSWORD( jhtp6 jhtp6 ), Select_priv= Y, Insert_priv= Y, Update_priv= Y, Delete_priv= Y, Create_priv= Y, Drop_priv= Y, References_priv= Y, Execute_priv= Y ; mysql> > FLUSH PRIVILEGES; mysql> > exit; 37

Creating Database books in MySQL Create books database Open Command Prompt Change to the C:\mysql mysql\bin directory Start database by executing the command C:\mysql mysql\bin\mysqld Copy SQL script books.sql to C:\mysql mysql\bin directory Open another Command Prompt Change to the C:\mysql mysql\bin directory Create the books database by executing the command C:\mysql mysql\bin> bin>mysql h localhost u u jhtp6 p p < books.sql 38

Manipulating Databases with JDBC Connect to a database Query the database Display the results of the query in JTable 39

Connecting to and Querying a Database DisplayAuthors Retrieves the entire authors table Displays the data in the standard output stream Example illustrates o Connect to the database o Query the database o Process the result 40

1 // Fig. 25.25: DisplayAuthors.java 2 // Displaying the contents of the authors table. 3 import java.sql.connection; 4 import java.sql.statement; 5 import java.sql.drivermanager; 6 import java.sql.resultset; 7 import java.sql.resultsetmetadata; 8 import java.sql.sqlexception; 9 10 public class DisplayAuthors 11 { 12 // JDBC driver name and database URL 13 static final String JDBC_DRIVER = "com.mysql.jdbc.driver"; 14 static final String DATABASE_URL = "jdbc:mysql://localhost/books"; 15 16 // launch the application 17 public static void main( String args[] ) 18 { 19 Connection connection = null; // manages connection 20 Statement statement = null; // query statement 21 22 // connect to database books and query database 23 try 24 { 25 Class.forName( JDBC_DRIVER ); // load database driver class 26 27 // establish connection to database 28 connection = Imports the JDBC classes and interfaces from package java.sql Declare a String constant that specifies the JDBC driver s class name Declare a String constant that specifies the database URL Loads the class definition for the database driver. Declare and initialize a Connection reference called connection. 29 DriverManager.getConnection( ΠΠΜ 500: Προχωρημένη Ανάπτυξη DATABASE_URL, Λογισμικού Εφαρμογών "jhtp6", Μηχανικής "jhtp6" ); 30 41

31 // create Statement for querying database 32 statement = connection.createstatement(); 33 34 // query database 35 ResultSet resultset = statement.executequery( 36 "SELECT authorid, firstname, lastname FROM authors" ); 37 Obtains the metadata 38 // process query results for the ResultSet. 39 ResultSetMetaData metadata = resultset.getmetadata(); 40 int numberofcolumns = metadata.getcolumncount(); 41 System.out.println( "Authors Table of Books Database:" ); 42 43 for ( int i = 1; i <= numberofcolumns; i++ ) 44 System.out.printf( "%-8s\t", metadata.getcolumnname( i ) ); 45 System.out.println(); 46 47 while ( resultset.next() ) 48 { 49 for ( int i = 1; i <= numberofcolumns; i++ ) 50 System.out.printf( "%-8s\t", resultset.getobject( i ) ); 51 System.out.println(); 52 } // end while 53 } // end try 54 catch ( SQLException sqlexception ) 55 { 56 sqlexception.printstacktrace(); 57 System.exit( 1 ); 58 } // end catch Invokes Connection method createstatement to obtain an object that implements interface Statement. Position the ResultSet cursor to the first row in the ResultSet with method next Use the Statement object s executequery method to execute a query that selects all the author information from table authors. Uses ResultSetMetaData method getcolumncount to retrieve the number of columns in the ResultSet. Extract the contents of one column in the current row Catch SQLException, which is thrown if the query execution or ResultSet process fails Obtain column name using method getcolumnname 42

59 catch ( ClassNotFoundException classnotfound ) 60 { 61 classnotfound.printstacktrace(); 62 System.exit( 1 ); 63 } // end catch 64 finally // ensure statement and connection are closed properly 65 { 66 try 67 { 68 statement.close(); 69 connection.close(); 70 } // end try 71 catch ( Exception exception ) 72 { 73 exception.printstacktrace(); 74 System.exit( 1 ); 75 } // end catch 76 } // end finally 77 } // end main 78 } // end class DisplayAuthors Authors Table of Books Database: authorid firstname lastname 1 Harvey Deitel 2 Paul Deitel 3 Tem Nieto 4 Sean Santry ClassNotFoundException is thrown if the class loader cannot locate the driver class Close the Statement and the database Connection. 43

JDBC driver types. Type Description 1 The JDBC-to-ODBC bridge driver connects Java programs to Microsoft ODBC (Open Database Connectivity) data sources. The Java 2 Software Development Kit from Sun Microsystems, Inc. includes the JDBC-to-ODBC Bridge driver (sun.jdbc.odbc.jdbcodbcdriver). This driver typically requires the ODBC driver on the client computer and normally requires configuration of ODBC data sources. The Bridge driver was introduced primarily for development purposes, before other types of drivers were available, and should not be used for production applications. 2 Native-API, partly Java drivers enable JDBC programs to use databasespecific APIs (normally written in C or C++) that allow client programs to access databases via the Java Native Interface (JNI). JNI is a bridge between a JVM and code written and compiled in a platform-specific language such as C or C++. Such code is known as native code. JNI enables Java applications to interact with native code. A Type 2 driver translates JDBC into databasespecific calls. Type 2 drivers were introduced for reasons similar to the Type 1 ODBC bridge driver. 3 Pure Java client to server drivers take JDBC requests and translate them into a network protocol that is not database specific. These requests are sent to a server, which translates the database requests into a database-specific protocol. 4 Pure Java drivers implement database-specific network protocols, so that Java programs can connect directly to a database. 44

Software Engineering Observations Most major database vendors provide their own JDBC database drivers, and many third-party vendors provide JDBC drivers as well. For more information on JDBC drivers, visit the Sun Microsystems JDBC Web site, servlet.java.sun.com/products/jdbc/drivers. On the Microsoft Windows platform, most databases support access via Open Database Connectivity (ODBC). ODBC is a technology developed by Microsoft to allow generic access to disparate database systems on the Windows platform (and some UNIX platforms). The JDBC-to to-odbc Bridge allows any Java program to access any ODBC data source. The driver is class JdbcOdbcDriver in package sun.jdbc.odbc. Most database management systems require the user to log in before accessing the database contents. DriverManager method getconnection is overloaded with versions that enable the program to supply the user name and d password to gain access. 45

Metadata enables programs to process ResultSet contents dynamically when detailed information about the ResultSet is not known in advance. Initially, a ResultSet cursor is positioned before the first row. Attempting to access a ResultSet s contents before positioning the ResultSet cursor to the first row with method next causes a SQLException. If a query specifies the exact columns to select from the database, the ResultSet contains the columns in the specified order. In this case, using the column number to obtain the column s s value is more efficient than using the column name. The column number provides direct access to the specified column. Using the column name requires a linear search of the column names to locate the appropriate column. Each Statement object can open only one ResultSet object at a time. When a Statement returns a new ResultSet,, the Statement closes the prior ResultSet. To use multiple ResultSets in parallel, separate Statement objects must return the ResultSets. 46

Popular JDBC driver names and database URL. RDBMS JDBC driver name Database URL format MySQL ORACLE com.mysql.jdbc.driver oracle.jdbc.driver.oracledr iver jdbc:mysql://hostname/databasena me jdbc:oracle:thin:@hostname:port Number:databaseName DB2 COM.ibm.db2.jdbc.net.DB2Dri ver jdbc:db2:hostname:portnumber/data basename Sybase com.sybase.jdbc.sybdriver jdbc:sybase:tds:hostname:portnub er/databasename 47

Common Programming Errors Specifying column number 0 when obtaining values from a ResultSet causes a SQLException. Attempting to manipulate a ResultSet after closing the Statement that created the ResultSet causes a SQLException.. The program discards the ResultSet when the corresponding Statement is closed. 48

Querying the books Database 1 // Fig. 25.28: ResultSetTableModel.java 2 // A TableModel that supplies ResultSet data to a JTable. 3 import java.sql.connection; 4 import java.sql.statement; 5 import java.sql.drivermanager; 6 import java.sql.resultset; 7 import java.sql.resultsetmetadata; 8 import java.sql.sqlexception; 9 import javax.swing.table.abstracttablemodel; 10 11 // ResultSet rows and columns are counted from 1 and JTable 12 // rows and columns are counted from 0. When processing 13 // ResultSet rows or columns for use in a JTable, it is 14 // necessary to add 1 to the row or column number to manipulate 15 // the appropriate ResultSet column (i.e., JTable column 0 is 16 // ResultSet column 1 and JTable row 0 is ResultSet row 1). 17 public class ResultSetTableModel extends AbstractTableModel 18 { 19 private Connection connection; 20 private Statement statement; 21 private ResultSet resultset; 22 private ResultSetMetaData metadata; 23 private int numberofrows; 24 25 // keep track of database connection status 26 private boolean connectedtodatabase = false; 27 Class ResultSetTableModel extends class AbstractTableModel, which implements interface TableModel. Instance variable keeps track of database connection status 49

28 // constructor initializes resultset and obtains its meta data object; 29 // determines number of rows 30 public ResultSetTableModel( String driver, String url, 31 String username, String password, String query ) 32 throws SQLException, ClassNotFoundException 33 { 34 // load database driver class 35 Class.forName( driver ); 36 37 // connect to database 38 connection = DriverManager.getConnection( url, username, password ); 39 40 // create Statement to query database 41 statement = connection.createstatement( 42 ResultSet.TYPE_SCROLL_INSENSITIVE, 43 ResultSet.CONCUR_READ_ONLY ); 44 45 // update database connection status 46 connectedtodatabase = true; 47 48 // set query and execute it 49 setquery( query ); 50 } // end constructor ResultSetTableModel 51 Constructor accepts five String arguments the driver class name, the database URL, the username, the password and the default query to perform Establishes a connection to the database. Invokes Connection method createstatement to create a Statement object. Indicate that connect to database is successful Invokes ResultSetTableModel method setquery to perform the default query. 50

52 // get class that represents column type 53 public Class getcolumnclass( int column ) throws IllegalStateException 54 { 55 // ensure database connection is available 56 if (!connectedtodatabase ) 57 throw new IllegalStateException( "Not Connected to Database" ); 58 59 // determine Java class of column 60 try 61 { 62 String classname = metadata.getcolumnclassname( column + 1 ); 63 64 // return Class object that represents classname 65 return Class.forName( classname ); Loads the class definition for the class and 66 } // end try returns the corresponding Class object. 67 catch ( Exception exception ) 68 { 69 exception.printstacktrace(); 70 } // end catch 71 72 return Object.class; // if problems occur above, assume type Object 73 } // end method getcolumnclass 74 Override method getcolumnclass to obtain a Class object that represents the superclass of all objects in a particular column Verify database connection status Obtains the fully qualified class name for the specified column. Returns the default type. 51

75 // get number of columns in ResultSet 76 public int getcolumncount() throws IllegalStateException 77 { 78 // ensure database connection is available 79 if (!connectedtodatabase ) 80 throw new IllegalStateException( "Not Connected to Database" ); 81 82 // determine number of columns 83 try 84 { 85 return metadata.getcolumncount(); 86 } // end try 87 catch ( SQLException sqlexception ) 88 { 89 sqlexception.printstacktrace(); 90 } // end catch 91 92 return 0; // if problems occur above, return 0 for number of columns 93 } // end method getcolumncount Override method getcolumnname to 94 obtain the name of the column in the 95 // get name of a particular column in ResultSet model s underlying ResultSet 96 public String getcolumnname( int column ) throws IllegalStateException 97 { 98 // ensure database connection is available 99 if (!connectedtodatabase ) 100 throw new IllegalStateException( "Not Connected to Database" ); 101 Override method getcolumncount to obtain the number of columns in the model s underlying ResultSet Obtains the number of columns in the ResultSet. 52

102 // determine column name 103 try 104 { 105 return metadata.getcolumnname( column + 1 ); 106 } // end try 107 catch ( SQLException sqlexception ) 108 { 109 sqlexception.printstacktrace(); 110 } // end catch 111 112 return ""; // if problems, return empty string for column name 113 } // end method getcolumnname 114 115 // return number of rows in ResultSet 116 public int getrowcount() throws IllegalStateException 117 { 118 // ensure database connection is available 119 if (!connectedtodatabase ) 120 throw new IllegalStateException( "Not Connected to Database" ); 121 122 return numberofrows; 123 } // end method getrowcount 124 Obtains the column name from the ResultSet. Override method getrowcount to obtain the number of rows in the model s underlying ResultSet 53

125 // obtain value in particular row and column 126 public Object getvalueat( int row, int column ) 127 throws IllegalStateException 128 { 129 // ensure database connection is available 130 if (!connectedtodatabase ) 131 throw new IllegalStateException( "Not Connected to Database" ); 132 133 // obtain a value at specified ResultSet row and column 134 try 135 { 136 resultset.absolute( row + 1 ); 137 return resultset.getobject( column + 1 ); 138 } // end try 139 catch ( SQLException sqlexception ) 140 { 141 sqlexception.printstacktrace(); 142 } // end catch 143 144 return ""; // if problems, return empty string object 145 } // end method getvalueat 146 147 // set new database query string 148 public void setquery( String query ) 149 throws SQLException, IllegalStateException 150 { 151 // ensure database connection is available 152 if (!connectedtodatabase ) 153 throw new IllegalStateException( "Not Connected to Database" ); 154 Override method getvalueat to obtain the Object in a particular row and column of the model s underlying ResultSet Uses ResultSet method absolute to position the ResultSet cursor at a specific row. Uses ResultSet method getobject to obtain the Object in a specific column of the current row. 54

155 // specify query and execute it 156 resultset = statement.executequery( query ); 157 158 // obtain meta data for ResultSet 159 metadata = resultset.getmetadata(); 160 161 // determine number of rows in ResultSet 162 resultset.last(); // move to last row 163 numberofrows = resultset.getrow(); // get row number 164 165 // notify JTable that model has changed 166 firetablestructurechanged(); 167 } // end method setquery 168 Executes the query to obtain a new ResultSet. Uses ResultSet method last to position the ResultSet cursor at the last row in the ResultSet. Uses ResultSet method getrow to obtain the row number for the current row in the ResultSet. Invokes method firetableastructurechanged to notify any JTable using this ResultSetTableModel object as its model that the structure of the model has changed. 55

169 // close Statement and Connection 170 public void disconnectfromdatabase() 171 { 172 if (!connectedtodatabase ) 173 return; 174 175 // close Statement and Connection 176 try 177 { 178 statement.close(); 179 connection.close(); 180 } // end try 181 catch ( SQLException sqlexception ) 182 { 183 sqlexception.printstacktrace(); 184 } // end catch 185 finally // update database connection status 186 { 187 connectedtodatabase = false; 188 } // end finally 189 } // end method disconnectfromdatabase 190 } // end class ResultSetTableModel Method disconnectfromdatabase implement an appropriate termination method for class ResultSetTableModel Verify whether the connection is already terminated Close the Statement and Connection if a ResultSetTableModel object is garbage collected. Set connectedtodatabase to false to ensure that clients do not use an instance of ResultSetTableModel after that instance has already been terminated 56

Portability Tips Some JDBC drivers do not support scrollable ResultSets.. In such cases, the driver typically returns a ResultSet in which the cursor can move only forward. For more information, see your database driver documentation. Some JDBC drivers do not support updatable ResultSets.. In such cases, the driver typically returns a read-only ResultSet.. For more information, see your database driver documentation. 57

Common Programming Error Attempting to update a ResultSet when the database driver does not support updatable ResultSets causes SQLExceptions. Attempting to move the cursor backwards through a ResultSet when the database driver does not support backwards scrolling causes a SQLException. 58

ResultSet constants for specifying ResultSet type. ResultSet static type constant TYPE_FORWARD_ONLY Description Specifies that a ResultSet s cursor can move only in the forward direction (i.e., from the first row to the last row in the ResultSet). TYPE_SCROLL_INSENSITIVE Specifies that a ResultSet s cursor can scroll in either direction and that the changes made to the ResultSet during ResultSet processing are not reflected in the ResultSet unless the program queries the database again. TYPE_SCROLL_SENSITIVE Specifies that a ResultSet s cursor can scroll in either direction and that the changes made to the ResultSet during ResultSet processing are reflected immediately in the ResultSet. 59

ResultSet constants for specifying result properties. ResultSet static concurrency constant CONCUR_READ_ONLY CONCUR_UPDATABLE Description Specifies that a ResultSet cannot be updated (i.e., changes to the ResultSet contents cannot be reflected in the database with ResultSet s update methods). Specifies that a ResultSet can be updated (i.e., changes to the ResultSet contents can be reflected in the database with ResultSet s update methods). 60

1 // Fig. 25.31: DisplayQueryResults.java 2 // Display the contents of the Authors table in the 3 // Books database. 4 import java.awt.borderlayout; 5 import java.awt.event.actionlistener; 6 import java.awt.event.actionevent; 7 import java.awt.event.windowadapter; 8 import java.awt.event.windowevent; 9 import java.sql.sqlexception; 10 import javax.swing.jframe; 11 import javax.swing.jtextarea; 12 import javax.swing.jscrollpane; 13 import javax.swing.scrollpaneconstants; 14 import javax.swing.jtable; 15 import javax.swing.joptionpane; 16 import javax.swing.jbutton; 17 import javax.swing.box; 18 19 public class DisplayQueryResults extends JFrame 20 { 21 // JDBC driver and database URL 22 static final String JDBC_DRIVER = "com.mysql.jdbc.driver"; 23 static final String DATABASE_URL = "jdbc:mysql://localhost/books"; 24 static final String USERNAME= "jhtp6"; 25 static final String PASSWORD= "jhtp6"; 26 Declare the database driver class name, database URL, username and password for accessing the database 61

27 // default query selects all rows from authors table 28 static final String DEFAULT_QUERY = "SELECT * FROM authors"; 29 30 private ResultSetTableModel tablemodel; 31 private JTextArea queryarea; 32 33 // create ResultSetTableModel and GUI 34 public DisplayQueryResults() 35 { 36 super( "Displaying Query Results" ); 37 38 // create ResultSetTableModel and display database table 39 try 40 { 41 // create TableModel for results of query SELECT * FROM authors 42 tablemodel = new ResultSetTableModel( JDBC_DRIVER, DATABASE_URL, 43 USERNAME, PASSWORD, DEFAULT_QUERY ); 44 45 // set up JTextArea in which user types queries 46 queryarea = new JTextArea( DEFAULT_QUERY, 3, 100 ); 47 queryarea.setwrapstyleword( true ); 48 queryarea.setlinewrap( true ); 49 50 JScrollPane scrollpane = new JScrollPane( queryarea, 51 ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, 52 ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER ); 53 54 // set up JButton for submitting queries 55 JButton submitbutton = new JButton( "Submit Query" ); 56 Declare the default query Declare tablemodel to be a reference to ResultSetTableModel Create TableModel for results of default query SELECT * FROM authors 62

57 // create Box to manage placement of queryarea and 58 // submitbutton in GUI 59 Box box = Box.createHorizontalBox(); 60 box.add( scrollpane ); 61 box.add( submitbutton ); 62 63 // create JTable delegate for tablemodel 64 JTable resulttable = new JTable( tablemodel ); 65 66 // place GUI components on content pane 67 add( box, BorderLayout.NORTH ); 68 add( new JScrollPane( resulttable ), BorderLayout.CENTER ); 69 70 // create event listener for submitbutton 71 submitbutton.addactionlistener( 72 73 new ActionListener() 74 { 75 // pass query to table model 76 public void actionperformed( ActionEvent event ) 77 { 78 // perform a new query 79 try 80 { 81 tablemodel.setquery( queryarea.gettext() ); 82 } // end try 83 catch ( SQLException sqlexception ) 84 { 85 JOptionPane.showMessageDialog( null, 86 sqlexception.getmessage(), "Database error", 87 JOptionPane.ERROR_MESSAGE ); 88 Create JTable delegate for tablemodel Register an event handler for the submitbutton that the user clicks to submit a query to the database Invoke ResultSetTableModel method setquery to execute the new query 63

89 // try to recover from invalid user query 90 // by executing default query 91 try 92 { 93 tablemodel.setquery( DEFAULT_QUERY ); 94 queryarea.settext( DEFAULT_QUERY ); 95 } // end try 96 catch ( SQLException sqlexception2 ) 97 { 98 JOptionPane.showMessageDialog( null, 99 sqlexception2.getmessage(), "Database error", 100 JOptionPane.ERROR_MESSAGE ); 101 102 // ensure database connection is closed 103 tablemodel.disconnectfromdatabase(); 104 105 System.exit( 1 ); // terminate application 106 } // end inner catch 107 } // end outer catch 108 } // end actionperformed 109 } // end ActionListener inner class 110 ); // end call to addactionlistener 111 112 setsize( 500, 250 ); // set window size 113 setvisible( true ); // display window 114 } // end try 115 catch ( ClassNotFoundException classnotfound ) Ensure that the database connection is closed 64

116 { 117 JOptionPane.showMessageDialog( null, 118 "MySQL driver not found", "Driver not found", 119 JOptionPane.ERROR_MESSAGE ); 120 121 System.exit( 1 ); // terminate application 122 } // end catch 123 catch ( SQLException sqlexception ) 124 { 125 JOptionPane.showMessageDialog( null, sqlexception.getmessage(), 126 "Database error", JOptionPane.ERROR_MESSAGE ); 127 128 // ensure database connection is closed 129 tablemodel.disconnectfromdatabase(); 130 131 System.exit( 1 ); // terminate application 132 } // end catch 133 134 // dispose of window when user quits application (this overrides 135 // the default of HIDE_ON_CLOSE) 136 setdefaultcloseoperation( DISPOSE_ON_CLOSE ); 137 138 // ensure database connection is closed when user quits application 139 addwindowlistener( 140 Ensure that the database connection is closed 65

141 new WindowAdapter() 142 { 143 // disconnect from database and exit when window has closed 144 public void windowclosed( WindowEvent event ) 145 { 146 tablemodel.disconnectfromdatabase(); 147 System.exit( 0 ); 148 } // end method windowclosed 149 } // end WindowAdapter inner class 150 ); // end call to addwindowlistener 151 } // end DisplayQueryResults constructor 152 153 // execute application 154 public static void main( String args[] ) 155 { 156 new DisplayQueryResults(); 157 } // end main 158 } // end class DisplayQueryResults Ensure that the database connection is closed when window has closed 66

67

Stored Procedure Stored procedures Store SQL statements in a database Invoke SQL statements by programs accessing the database Interface CallableStatement Receive arguments Output parameters 68

Portability Tips Although the syntax for creating stored procedures differs across s database management systems, interface CallableStatement provides a uniform interface for specifying input and output parameters for stored procedures and for invoking stored procedures. According to the Java API documentation for interface CallableStatement, for maximum portability between database systems, programs should d process the update counts or ResultSets returned from a CallableStatement before obtaining the values of any output parameters. 69

RowSet Interface Interface RowSet Configures the database connection automatically Prepares query statements automatically Provides set methods to specify the properties needed to establish sh a connection Part of the javax.sql package Two types of RowSet Connected RowSet o Connects to database once and remain connected Disconnected RowSet o Connects to database, executes a query and then closes connection 70

Package javax.sql.rowset JdbcRowSet o o o Connected RowSet Wrapper around a ResultSet Scrollable and updatable by default CachedRowSet o o o o Disconnected RowSet Cache the data of ResultSet in memory Scrollable and updatable by default Serializable Can be passed between Java application o Limitation Amount of data that can be stored in memory is limited 71

1 // Fig. 25.32: JdbcRowSetTest.java 2 // Displaying the contents of the authors table using JdbcRowSet. 3 import java.sql.resultsetmetadata; 4 import java.sql.sqlexception; 5 import javax.sql.rowset.jdbcrowset; 6 import com.sun.rowset.jdbcrowsetimpl; // Sun s JdbcRowSet implementation 7 8 public class JdbcRowSetTest 9 { 10 // JDBC driver name and database URL 11 static final String JDBC_DRIVER = "com.mysql.jdbc.driver"; 12 static final String DATABASE_URL = "jdbc:mysql://localhost/books"; 13 static final String USERNAME = "jhtp6"; 14 static final String PASSWORD = "jhtp6"; 15 16 // constructor connects to database, queries database, processes 17 // results and displays results in window 18 public JdbcRowSetTest() 19 { 20 // connect to database books and query database 21 try 22 { 23 Class.forName( JDBC_DRIVER ); // load database driver class 24 25 // specify properties of JdbcRowSet 26 JdbcRowSet rowset = new JdbcRowSetImpl(); 27 rowset.seturl( DATABASE_URL ); // set database URL 28 rowset.setusername( USERNAME ); // set username 29 rowset.setpassword( PASSWORD ); // set password 30 rowset.setcommand( "SELECT * FROM authors" ); // set query 31 rowset.execute(); // execute query 32 Use Sun s reference implementation of JdbcRowSet interface (JdbcRowSetImpl) to create a JdbcRowSet object Invoke JdbcRowSet method seturl to specify the database URL Invoke JdbcRowSet method setusername to specify the username Invoke JdbcRowSet method setusername to specify the password Invoke JdbcRowSet method setcommand to specify the query ΠΠΜ 500: Προχωρημένη Ανάπτυξη Λογισμικού Εφαρμογών Invoke Μηχανικής JdbcRowSet method execute to execute the query 72

33 // process query results 34 ResultSetMetaData metadata = rowset.getmetadata(); 35 int numberofcolumns = metadata.getcolumncount(); 36 System.out.println( "Authors Table of Books Database:" ); 37 38 // display rowset header 39 for ( int i = 1; i <= numberofcolumns; i++ ) 40 System.out.printf( "%-8s\t", metadata.getcolumnname( i ) ); 41 System.out.println(); 42 43 // display each row 44 while ( rowset.next() ) 45 { 46 for ( int i = 1; i <= numberofcolumns; i++ ) 47 System.out.printf( "%-8s\t", rowset.getobject( i ) ); 48 System.out.println(); 49 } // end while 50 } // end try 51 catch ( SQLException sqlexception ) 52 { 53 sqlexception.printstacktrace(); 54 System.exit( 1 ); 55 } // end catch 56 catch ( ClassNotFoundException classnotfound ) 57 { 58 classnotfound.printstacktrace(); 59 System.exit( 1 ); 60 } // end catch 61 } // end DisplayAuthors constructor 62 73

63 // launch the application 64 public static void main( String args[] ) 65 { 66 JdbcRowSetTest window = new JdbcRowSetTest(); 67 } // end main 68 } // end class JdbcRowSetTest Authors Table of Books Database: authorid firstname lastname 1 Harvey Deitel 2 Paul Deitel 3 Tem Nieto 4 Sean Santry 74