Download presentation
Presentation is loading. Please wait.
Published byВиктор Мещеринов Modified over 5 years ago
1
CS3220 Web and Internet Programming Database Access with JDBC
Chengyu Sun California State University, Los Angeles
2
Client-Server Architecture of Databases
mysql MySQL Workbench PHPMyAdmin … Applications DB DB DB A library that sends SQL and other commands from client to server, and get the results from server to client.
3
JDBC Java Program JDBC Driver DB Server JDBC API DBMS MySQL
Independent MySQL
4
About JDBC Java DataBase Connectivity JDBC API is DBMS independent
JDBC Driver implements JDBC API for a particular DBMS
5
Example: HelloJDBC.java
Make connections Execute queries Process results Handle exceptions (and close connections)
6
JDBC Basics … import java.sql.*; Create connection URL
jdbc:mysql://[host:port]/[database][?user=cs3220stu31&password=abcd] DriverManager.getConnection( URL ) DriverManager.getConnection( URL, user, pass )
7
… JDBC Basics Create statement Get result back
Statement stmt = c.createStatement(); stmt.executeQuery(String sql) stmt.executeUpdate(String sql) Get result back ResultSet rs
8
About Loading JDBC Driver …
try { Class.forName( "com.mysql.jdbc.Driver" ); } catch( ClassNotFoundException e ) throw new ServletException( e ); See an example at
9
… About Loading JDBC Driver
Needed for older version of Java (before version 6) Needed for older version of MySQL JDBC driver (before version 8) Only needs to be done once per project (not once per servlet)
10
DB Query Results In a program, we want to Access each record
Access each attribute in a record Access the name of each attribute select * from items; name price quantity Milk 3.89 2 Beer 6.99 1
11
JDBC ResultSet – Row Access
Cursor Record 1 Record 2 Record 3 … Results next() – move cursor down one row Cursor starts from before the 1st record true if the current record is valid false if no more records
12
Common Code for Processing ResultSet
Process each row while(rs.next()) {…} Check whether a result set is empty if(rs.next()) {…}
13
JDBC ResultSet – Column Access
Access the columns of current row getXxx( String columnName ) E.g. getString( “user” ); getXxx( int columnIndex ) columnIndex starts from 1 E.g. getString( 1 );
14
JDBC ResultSet – Access Column Names
ResultSetMetaData meta = rs.getMetaData(); ResultSetMetaData getColumnName( columnIndex ) Column name getColumnLabel( columnIndex ) Column title for display or printout
15
Handle Exceptions catch( SQLException e ) { e.printStackTrace(); }
finally try if( c != null ) c.close();
16
Example: GuestBook (JDBC) – Display
Create a guest_book table Retrieve the entries in a servlet Display the entries in a JSP
17
Example: GuestBook (JDBC) – Add
Save new guest book entries to the database executeQuery() vs. executeUpdate() Potential problems of handing user input Special characters SQL injection attack
18
Example: SQL Injection Attack
User input should NOT be trusted Regular user input Username: cysun Password: abcd Malicious user input Username: someuser Password: something’ or ‘1 Prevent SQL injection attack?
19
Prepared Statements Statements with parameters
String sql = “insert into items values (?, ?, ?)”; PreparedStatement pstmt =c.prepareStatement(sql); pstmt.setString(1, “orange”); pstmt.setBigDecimal(2, 0.59); pstmt.setInt(3, 4); pstmt.executeUpdate();
20
Benefits of Prepared Statements
Special characters are properly handled Secure if the SQL statement is constructed from user input The SQL statement is more readable Better performance
21
Beyond the Basics ... Transaction ACID transaction disable auto commit
send queries/updates commit enable auto commit exception rollback
22
... Beyond the Basics ... It’s rather expensive to open a db connection So how about once we open a connection, we leave it open forever?? Connection Pool Max number of connections Max number of idle connections And many other configurable parameters
23
... Beyond the Basics Mismatch between an OO design and a relational design Object-Relational Mapping JPA and Hibernate -
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.