09 JDBC
09 JDBC
May 12, 2008 Sprenkle - CS297 1 May 12, 2008 Sprenkle - CS297 2
May 12, 2008 Sprenkle - CS297 3 May 12, 2008 Sprenkle - CS297 4
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
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()
}
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
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