csci 6962: server-side design and programming jdbc database programming
TRANSCRIPT
![Page 1: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/1.jpg)
CSCI 6962: Server-side Design and Programming
JDBC Database Programming
![Page 2: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/2.jpg)
Outline
• Introduction to JDBC• Connecting to a database server• Executing queries and reading result sets• Prepared statements• Executing update statements• Synchronized database access
![Page 3: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/3.jpg)
JDBC Definition• Java Database Connectivity (JDBC):
set of classes that provide methods to– Connect to a database through a database server (using a driver)– Query database using SQL syntax, getting “list” of records that
match query– Manipulate database by executing SQL commands to modify, insert,
and delete records
web container
JSF page
Managed bean database
database driver
DBMS
database server
JDBC
![Page 4: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/4.jpg)
JDBC Components
• Major objects involved:– Connection: represents connection to a database through a server – Statement: represents SQL statement executed on database via
that connection – ResultSet: represents “list” of records matching a query
Database server
database
Statement objectselect * from widgets
ResultSet objectID name price ID name price ID name price
![Page 5: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/5.jpg)
Connecting to the Database Server• Load the database driver
– Not necessary in most recent version, but safe thing to do
Syntax: Class.forName("driver class").newInstance();
• Name of driver class based on provider (see their documentation)– Derby: org.apache.derby.jdbc.ClientDriver– MySQL: com.mysql.jdbc.Driver
![Page 6: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/6.jpg)
Connecting to the Database Server
• Need to provide url of database• Form: jdbc:servertype:serverURL:port/databasename
– Derby: jdbc:derby://localhost:1527/DBname– MySQL: jdbc:mysql://localhost:3306/Dbname
![Page 7: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/7.jpg)
Connecting to the Database Server• Syntax:connectionobject = DriverManager.getConnection("databaseURL",
"username", "password");
• Derby example:
• Should close connection when doneconnectionobject.close();
![Page 8: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/8.jpg)
Exception Handling in JDBC• Any database-related statement may throw SQLException
– Your code must put in try/catch block– May also need to catch other exceptions
• ClassNotFoundException for missing database driver
Diagnostic message displayed
Better idea: Redirect to an error page
![Page 9: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/9.jpg)
Connecting to the Database Server
![Page 10: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/10.jpg)
Executing Queries• Create new statement object using the connection• Execute an SQL query using that statement• Store results in a ResultSet object
• Syntax:statement = connection.createStatement();statement.executeQuery(“SQL query”);
![Page 11: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/11.jpg)
Reading ResultSets• Can only do simple access:
– Read in field values from current record – Move to next record
• Syntax to move to next record: ResultSetObject.next();– Returns false if no next record, true otherwise– Must execute once before reading first record– Usually while loop to read until no more records
while(ResultSetObject.next()) { code to read in current record}
![Page 12: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/12.jpg)
Reading ResultSets
• Syntax to read field from current record: value = ResultSetObject.getType(fieldname);
Specify field name used in database
Specify type data is to be read in as
varChar getStringint getIntdouble getDouble
![Page 13: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/13.jpg)
Widget Example
• Goal: Display all Widgets in datatable– Same as before, but no longer hardwired
• Database access in Widget class• getAllWidgets:
– Queries for all widgets, extracts ID of each widget– Constructs widget with that ID, adds to list
• Constructor:– Queries for widget with given ID– Extracts name, price to set its properties
![Page 14: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/14.jpg)
getAllWidgets Code
Execute SQL query for all widgets
Loop through all results
Get the value of the ID field
Close connection and return list
Use it to construct a widget and add to the list
![Page 15: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/15.jpg)
Inserting Parameter Values
• Queries often based on variables– Example: finding widget with given ID
• Must insert values into query – If value is string, must make sure quote marks ‘ ‘
surround the value!
Insert given ID into the query
![Page 16: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/16.jpg)
Constructor Code
Execute SQL query for widgets with given ID
Advance to first (and only) result
Extract name as string and price as double
![Page 17: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/17.jpg)
Prepared Statements• Tell database server basic form of statements in advance
– Database server can do all work for that type of statement once
• “Fill in blanks” for actual values when actually execute statement– Easier syntax than inserting manually– More secure against SQL injection attacks!
• Example: Extracting widget with given ID– All statements of form:
"SELECT * FROM widgets WHERE ID = ____“
![Page 18: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/18.jpg)
Prepared Statements
• Declare as PreparedStatementPreparedStatement lookup = null;
• Define prepared statement using connection.prepareStatement(template);
• Place ‘?’ where actual values will be inserted
lookup = connection.prepareStatement("SELECT * FROM widgets WHERE ID = ?");
![Page 19: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/19.jpg)
Prepared Statements
• Use setType (index, value) to insert value into statement
lookup.setString(1, ID);
• Execute query on the prepared statementresultsConstructor = lookup.executeQuery();
Type of field (like get method in ResultSet) Which ‘?’ to insert the value into
Insert ISBN into first (and only) ‘?’ in lookup
![Page 20: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/20.jpg)
Executing Update Statements
• Syntax:int chng = statement.executeUpdate(SQL) orint chng = preparedstatement.executeUpdate()
• Returns number of records changed by statement– Often used for validation
![Page 21: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/21.jpg)
Updating Price in Widget Class
![Page 22: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/22.jpg)
Performing Update from Bean• Call static Widget method with ID, price• If price changed, display new inventory• If no change, display error message in JSF page
![Page 23: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/23.jpg)
Synchronized Database Access• Database updates occur “simultaneously” on busy sites• Can interfere with one another• Example: Quantity update after purchase
– Query for previous quantity– Subtract 1– Update database with new quantity
![Page 24: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/24.jpg)
Synchronized Database Access• Java runs separate clients as “parallel” threads which
execute “simultaneously”– Processor swaps back and forth between threads
• Problem if following sequence occurs:– Current quantity = 100– Client 1 code to get current quantity executes (value = 100)– Processor swaps to client 2 thread– Client 2 code to get current quantity (value still = 100)– Client 2 code sets new quantity to 99 and stores in database– Processor swaps back to client 1 thread– Client 1 code also sets new quantity to 99 and stores in
database!
![Page 25: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/25.jpg)
Synchronized Database Access
Get quantity
Quantity = 100
Client 1 thread
Get quantity
Quantity = 100
Client 2 thread Set quantity = 99
Store 99 in database
Set quantity = 99
Store 99 in database
Problem: this code should not be interrupted!
![Page 26: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/26.jpg)
Synchronized Database Access
• Can declare sections of code to be synchronized– Only one thread may execute it at a time– Another thread cannot start the code until the first has finished it
• Syntax: synchronized(object) { code }
Only one thread at a time should be able to execute this code on this object
![Page 27: CSCI 6962: Server-side Design and Programming JDBC Database Programming](https://reader030.vdocuments.net/reader030/viewer/2022032707/56649e315503460f94b21b68/html5/thumbnails/27.jpg)
Synchronized Database Access