0% found this document useful (0 votes)
16 views

db JDBC

Uploaded by

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

db JDBC

Uploaded by

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

Introduction to Database

Programming with JDBC

• Kuldeep Kumar Yogi


• Banasthali University
JDBC/ODBC Overview
• ODBC and JDBC
– Open Database Connectivity (ODBC) is a standard software API for
connecting to database management systems (DBMS)
– JDBC is a Java API which provides classes and methods to easily
interact with all kinds of data sources

• JDBC implementation

• Many database related classes are organized in the “java.sql”


package

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

 Note: wrap these statements in “try…catch…” block since


many of these statements require exception handling
– ClassNotFoundException
– SQLException

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)

Connection con = DriverManager.getConnection(dsn, id, passwd);


Connection dc = DriverManager.getConnection("jdbc:mysql://localhost:3306/eilmt","root","root");
– dsn: “jdbc:odbc:northwind” //northwind is the dsn
– id: ODBC login id
– passwd: ODBC login password

5
Preparing and Executing SQL
Connection con = DriverManager.getConnection(dsn, id, passwd);
Statement stmt=con.createStatement();
String query="select * from products";

• Use the connection object to create a statement object

• Prepare a SQL query string

• Execute the statement


– Execution depends on the SQL statement type: read or write

6
Database Read
Statement stmt=con.createStatement();
String query="select * from products";
ResultSet rs=stmt.executeQuery(query);

• For a database read operation, use the


executeQuery() method of the statement object to
execute “select” SQL statements

• Use a ResultSet object to accept the retrieved data


– ResultSet represents retrieved data as a data table

7
ResultSet Processing
• ResultSet object (table) maintains a cursor pointing to only
one row at a time.

• By default, ResultSet is forward only and read only


– ResultSet type is determined when creating Statement object

• Read data by moving the cursor


– A while loop can be used to traverse all rows
– Initially (when the ResultSet object is successfully created) the cursor
is positioned before the first row
– Use the “next()” method to move to the next row
– When it moves after the last row, the method returns “false”

8
Getting Data from ResultSet
• Get row number (row starts from 1)
int rowNumber=rs.getRow();

• Get field values using getter methods


– rs.getString(String columnName) or
– rs.getString(int columnNumber)
• Column number starts from 1
• Usually used when a column is not explicitly named
– Note: the getter method can be used only once for the
same field

9
Last Step
• Close the connection the connection when all
database operations are performed
– This will also close all statement and result set
objects

• It is a good habit to close connection explicitly


for performance reasons

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

• Dynamic SQL statement construction can go complex and


confusing
– !! Make sure your SQL statement is constructed correctly
– Be careful of the use of single quotes
– Use prepared statement

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);

• “Write” operations include insertion, update and deletion

• Use the executeUpdate() method of the statement object to


execute these SQL statements;

• This method returns an “int” type value indicating the


number of rows affected
– What does it mean if “0” is returned

15
Reading Different Data Types
• Besides getString(), you can also use getInt(), getBoolean(),
getDouble(), etc, if column data type is known

• Number, Currency, AutoNumber


– rs.getInt() or rs.getDouble()

• 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

You might also like