0% found this document useful (0 votes)
17 views4 pages

09 JDBC

Uploaded by

subham220915
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views4 pages

09 JDBC

Uploaded by

subham220915
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Objectives Review: Databases

• Review: Databases • What do databases do for us?


• JDBC • What are tables made up of?
• Static Mock-up Demo • What language do we use to query and
update relational databases?
• What is the syntax for the SELECT
statement?

May 12, 2008 Sprenkle - CS297 1 May 12, 2008 Sprenkle - CS297 2

Project Overview JDBC: Java Datab


atabase Connectivity
Web Application • Database-independent connectivity
JDBC
 JDBC converts generalized JDBC calls into
HTML Servlets, Backend vendor-specific SQL calls
JSPs, … (Java) State
• Classes in java.sql.* and javax.sql.*
DB or XML or
Automatically Data structures, packages
text files
generate UI helper classes
(HTML), Handle
user requests

May 12, 2008 Sprenkle - CS297 3 May 12, 2008 Sprenkle - CS297 4

Using JDBC in a Java Program java.sql


java.sql.
.DriverManager
• Load the database driver • Provides a common access layer for
• Obtain a connection different database drivers
• Create and execute statements (SQL • Requires that each driver used by the
queries) application be registered before use
• Use result sets (tables) to navigate through • Load the database driver by its name using
the results ClassLoader:
• Close the connection Class.forName(“org.postgresql.Driver”);

May 12, 2008 Sprenkle - CS297 5 May 12, 2008 Sprenkle - CS297 6

1
JDBC: Creating a Connection JDBC: Executing Queries: Statements
• After loading the DB driver, create the connection Statement stmt = con.createStatement();
(see API for all ways)
Type of DB
Location of DB,
port optional DB name
• executeQuery(String query)
 Returns a ResultSet
String url = “jdbc:postgresql://hopper:5432/cs297";  Iterate through ResultSet, row-by-row, getting
Connection con = DriverManager.getConnection(url, results from each column
username, password);
rs = stmt.executeQuery(“SELECT * FROM table”);
• executeUpdate(String query) to
• Close connection when done update table
 Release resources
Where should these code
 Returns an integer representing the number of
con.close(); affected rows
fragments go in a Servlet?
May 12, 2008 Sprenkle - CS297 7 May 12, 2008 Sprenkle - CS297 8

Iterating Through ResultSets Useful ResultSet Methods


• Example: • Number of rows in the result:
ResultSet rs = stmt.executeQuery("SELECT” + rs.last();
“* FROM majors"); int numberOfRows = rs.getRow();

while( rs.next()) {
String name= rs.getString("name");
• Information about the table, such as number,
String dept = rs.getString(2); // column 2 types, and properties of columns:
System.out.println(name + "\t" + dept);  ResultSetMetaData getMetaData()
}

• Can access column values by name or which


column (count starts at 1, left to right)
May 12, 2008 Sprenkle - CS297 9 May 12, 2008 Sprenkle - CS297 10

JDBC: Prepared Statements JDBC


• con.prepareStatement(String template) • API Documentation: java.sql.*
 Compile SQL statement “templates”  Statements, Connections, ResultSets, etc. are
• Reuse statement, passing in parameters all Interfaces
 Java handles formatting of Strings, etc. as parameters • Driver/Library implements interfaces for its
updateSales = con.prepareStatement(“INSERT” + database
“INTO Majors (name, department) VALUES”+ • Limitations
“(?, ?)”); ? = Parameter  Java doesn’t compile the SQL statements
• Set parameters • Exact syntax depends on DB
 updateSales.setInt(1, 100); • Compile, run, verify queries outside of Java for
 updateSales.setString(2, “French Roast”); your database
 Columns start at 1 • Then copy and use in Java code
May 12, 2008 Sprenkle - CS297 11 May 12, 2008 Sprenkle - CS297 12

2
Using PostgreSQL on Command-Line Examples Using JDBC
• In a terminal, ssh into hopper
 ssh hopper
• Run the PostgreSQL client: psql ,
connecting to the appropriate database
 psql cs297
• At the prompt, type in SQL statements,
ending in ;

May 12, 2008 Sprenkle - CS297 13 May 12, 2008 Sprenkle - CS297 14

Transactions in JDBC Transactions in JDBC


• By default, a connection is in auto-commit • You can turn off auto-commit and execute
mode multiple statements as a transaction
 Each statement is a transaction  Database can keep handling others’ reads
 Automatically committed as soon as executed  Others won’t see updates until you commit
con.setAutoCommit(false);
// execute SQL statements …
con.commit(); // commit those statements
con.setAutoCommit(true);

• Can call rollback to abort updates


May 12, 2008 Sprenkle - CS297 15 May 12, 2008 Sprenkle - CS297 16

Storing Passwords Connection Pool


• Use md5 function on passwords • Want to reuse DB connections
 md5(‘password’)  Reduce overhead of creating and closing
• Compare user’s input password md5’d with connections to database
password in database • Could write our own connection pool class
 SELECT COUNT(id) FROM Users WHERE  Many examples online
username=? AND password=md5(?); • Apache wrote one that we’ll use
• Example: username and password = ‘test’  http://commons.apache.org/dbcp/
 Need to add its jars to our lib directory

May 12, 2008 Sprenkle - CS297 17 May 12, 2008 Sprenkle - CS297 18

3
Using the Connection Pool Midterm Info
• Create a DataSource object in the • Midterm - next Wednesday
ServletContext
• Covers
 All the servlets can see the ServletContext
 Shared resource, given name, value
 HTML, CSS
• Create a DBConnectionServlet class  WWW in general - distributed ideas
 init method gets the DataSource object from the  Usability
ServletContext  Servlets, JSPs, Application organization
 When need a connection, call getConnection on
 Synchronization, Version Control
DataSource object
 Servlets that need the DB extend
 SQL, JDBC
DBConnectionServlet
• Examples in Logic project later
May 12, 2008 Sprenkle - CS297 19 May 12, 2008 Sprenkle - CS297 20

TODO Issues
• Lab 7: JDBC • Welcome Page?
 Due Friday  Text from Professor Gregory?
• Study for midterm  Documentation links?
• In a bit: Static HTML Mock-up Demo • Logout link: Student, Professors
 From Logout: return to Welcome Page, with
message “You have logged out”
• Adding answers: needs the symbol table
• Deleting: before deleting, make sure that’s
really what the user wants

May 12, 2008 Sprenkle - CS297 21 May 12, 2008 Sprenkle - CS297 22

You might also like