db JDBC
db JDBC
• JDBC implementation
2
Database Configuration
• Setting up ODBC for MS Access
• Demo
– Source name:
“northwind”
3
Basic Process of Using JDBC
1. Load JDBC driver and establish connection to database
2. Prepare SQL statement
3. Execute the statement and process results
4. Close connection
4
Database Connection
1. Load/register JDBC-ODBC driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Class.forName("com.mysql.jdbc.Driver").newInstance();
2. Create a connection (object)
5
Preparing and Executing SQL
Connection con = DriverManager.getConnection(dsn, id, passwd);
Statement stmt=con.createStatement();
String query="select * from products";
6
Database Read
Statement stmt=con.createStatement();
String query="select * from products";
ResultSet rs=stmt.executeQuery(query);
7
ResultSet Processing
• ResultSet object (table) maintains a cursor pointing to only
one row at a time.
8
Getting Data from ResultSet
• Get row number (row starts from 1)
int rowNumber=rs.getRow();
9
Last Step
• Close the connection the connection when all
database operations are performed
– This will also close all statement and result set
objects
10
Web Database Application
Practices and Techniques
Dynamic SQL Generation
• Dynamically construct a query string based on user input and
choice
– User input values
– Multiple selection criteria
– Sorting selection
12
Use of PreparedStatement
String fileId= “Tr_0001_En.xml”;
PreparedStatement ps1=con.prepareStatement("Select meteor,BV from target where T_S_id like ?
");
ps1.setString(1,fileId.substring(0,7)+"%"+ "E"+eng_id +"%");
13
Fuzzy Search
• Use “like” operator for fuzzy search
– % multiple character wildcard
– _ single character wildcard
• Examples
– … where BookTitle like ‘%information%’
– … where BookTitle like ‘introduction%’
– … where FirstName like ‘Mc%’
14
Database Write
Statement stmt=con.createStatement();
String query=“update products set unitprice=200 where productid=1";
int rows=stmt.executeUpdate(query);
15
Reading Different Data Types
• Besides getString(), you can also use getInt(), getBoolean(),
getDouble(), etc, if column data type is known
• Yes/No
– rs.getBoolean()
• Date/Time
– rs.getDate()
– Date format processing
16
Resources
• SQL Tutorial
– http://sqlcourse.com/
– http://sqlcourse2.com/
• JDBC Tutorial
– http://java.sun.com/docs/books/tutorial/jdbc/index.html
• java.sql.* reference
– http://java.sun.com/j2se/1.4.2/docs/api/java/sql/package-summary.html
• JDBC documentation
– http://java.sun.com/j2se/1.5.0/docs/guide/jdbc/index.html
• Best practices
– http://www.precisejava.com/javaperf/j2ee/JDBC.htm
17