In this session you will learn:
Introduction to Databases
Advantages of Database Systems
Database Languages
Distributed Database
Relational Database Model
Structured Query Language (SQL)
Basic Ingredients of JDBC
Supplying Values for Prepared Statement Parameters
For more information, visit this link: https://www.mindsmapped.com/courses/software-development/online-java-training-for-beginners/
2. Page 1Classification: Restricted
Agenda
• Introduction to Databases
• Advantages of Database Systems
• Database Languages
• Distributed Database
• Relational Database Model
• Structured Query Language (SQL)
• Basic Ingredients of JDBC
• Supplying Values for Prepared Statement Parameters
3. Page 2Classification: Restricted
Introduction to Databases
• File processing
• Random access or sequential
• Only allow access to data
• Cannot query
• Database systems
• Mechanisms to organize and store data
• Allow sophisticated queries
• Relational database - most popular style
• Microsoft Access, Sybase, Oracle
• Structured Query Language (SQL, "sequel")
• Queries relational databases
• Can write Java programs to use SQL queries
4. Page 3Classification: Restricted
Database Systems
• Database systems
• Cheap, massive, direct access storage available
• Led to research in database systems
• Database - collection of data
• Database system
• Database
• Hardware (where data resides)
• Software
• Database management system (DBMS)
• Controls storage and retrieval
5. Page 4Classification: Restricted
Advantages of Database Systems
• Advantages
• Reduce redundancy
• Avoid inconsistency
• Share data
• Enforce standards
• Security restrictions
• Data integrity
• Balance conflicting requirements
• Non-database systems
• Each application has own files
• Redundant
• Lack centralized control
6. Page 5Classification: Restricted
Data Independence
• Data independence
• Applications not dependent on how data stored or accessed
• Data dependency
• Change in storage or retrieval technique forces program change
• Applications can have different views of data
• Change storage/retrieval strategy without changing applications
7. Page 6Classification: Restricted
Database Languages
• Database language
• Used to access database
• Can use high-level languages
• Java, C, C++, Visual Basic, COBOL, PL/I, Pascal
• Make requests using a specially designed query language
• Host language
• Host languages
• Database sublanguage (DSL) - specifics of database objects and
operations
• Combination of
• Data definition language (DDL) - defines database objects
• Data manipulation language (DML) - specifies processing
• SQL has DDL and DML
8. Page 7Classification: Restricted
Distributed Database
• Distributed database
• Spread across computers in network
• Data stored where frequently used
• Available to all users
• Advantages
• Control and economics of local processing
• Information access
• Disadvantages
• Costly
• Security risks
9. Page 8Classification: Restricted
Relational Database Model
• Database models
• Hierarchal, network, relational (most popular)
• Focus on relational
• Relational Database Model
• Logical representation of data
• Consider relationships between data
• Not concerned with implementation
10. Page 9Classification: Restricted
Relational Database Model
• Relational database
• Composed of tables
• Rows called records
• Columns are fields (attributes)
• First field usually primary key
• Unique for each record
• Primary key can be more than one field (column)
• Primary key not required
11. Page 10Classification: Restricted
Relational Database Model
Number Name Department Salary Location
23603
24568
35761
34589
47132
78321
JONES, A.
KERWIN, R.
LARSON, P.
MYERS, B.
NEUMANN, C.
STEPHENS, T.
413
413
642
611
413
611
1100
2000
1800
1400
9000
8000
NEW JERSEY
NEW JERSEY
LOS ANGELES
ORLANDO
NEW JERSEY
ORLANDO
Table: Employee
A record
A columnPrimary Key
12. Page 11Classification: Restricted
Relational Database Model
• Operations
• Projection
• Taking a subset of a table
• Join
• Combining tables to form a larger one
• Example
• Using previous tables, make list of departments and locations
13. Page 12Classification: Restricted
Relational Database Model
Number Name Department Salary Location
23603
24568
35761
34589
47132
78321
JONES, A.
KERWIN, R.
LARSON, P.
MYERS, B.
NEUMANN, C.
STEPHENS, T.
413
413
642
611
413
611
1100
2000
1800
1400
9000
8000
NEW JERSEY
NEW JERSEY
LOS ANGELES
ORLANDO
NEW JERSEY
ORLANDO
Table: Employee
Department Location
413
642
611
NEW JERSEY
LOS ANGELES
ORLANDO
Projection
(subset)
14. Page 13Classification: Restricted
Relational Database Model
•Advantages of relational databases
•Tables easy to use, understand, and implement
•Easy to convert other database structures into
relational scheme
• Universal
•Projection and join operations easy to
implement
•Searches faster than schemes with pointers
•Easy to modify - very flexible
•Greater clarity and visibility than other models
17. Page 16Classification: Restricted
Basic SELECT Query
• SELECT Query
• Selects information from one more tables
• Format
SELECT * FROM TableName
• Asterisk * - select all
• SELECT * FROM Authors
• Selects entire Authors table
• Selecting specific fields
• Replace asterisk (*) with comma separated list
• SELECT AuthorID, LastName FROM Authors
• Ordered left to right
AuthorID LastName
1 Deitel
2 Deitel
3 Nieto
18. Page 17Classification: Restricted
WHERE Clause
• Selection with criteria
• Only select data that meets requirement
•SELECT * FROM TableName WHERE criteria
• Example
SELECT * FROM Authors WHERE YearBorn > 1960
AuthorID FirstName LastName YearBorn
2 Paul Deitel 1968
3 Tem Nieto 1969
19. Page 18Classification: Restricted
WHERE Clause
• Conditions
• Can use <, >, <=, >=, =, <> and LIKE
• LIKE - used for pattern matching
• Search for similar strings
• Wildcard characters * and ?
• * - Any number of consecutive characters at asterisk's location
SELECT * FROM Authors WHERE LastName LIKE 'd*'
LastName starts with 'd' followed by any number of characters
AuthorID FirstName LastName YearBorn
1 Harvey Deitel 1946
2 Paul Deitel 1968
20. Page 19Classification: Restricted
WHERE Clause
• Conditions
• ? - any single character at location
SELECT * FROM Authors WHERE LastName LIKE '?i*'
• LastName begins with any character, 'i' for second character,
followed by any number of charactersAuthorID FirstName LastName YearBorn
3 Tem Nieto 1969
21. Page 20Classification: Restricted
WHERE Clause
• Conditions
• Range of characters
• [startValue-endValue]
SELECT * FROM Authors WHERE LastName LIKE '?[a-i]*'
• Start with any letter, second letter between a and i, followed by any
number of characters
• All authors fit range
AuthorID FirstName LastName YearBorn
1 Harvey Deitel 1946
2 Paul Deitel 1968
3 Tem Nieto 1969
22. Page 21Classification: Restricted
ORDER BY Clause
• Arrange results in order
SELECT * FROM TableName ORDER BY field ASC
SELECT * FROM TableName ORDER BY field DESC
• field - field used to order
• ASC/DESC - ascending/descending sort
• ASC default
SELECT * FROM Authors ORDER BY LastName ASC
AuthorID FirstName LastName YearBorn
2 Paul Deitel 1968
1 Harvey Deitel 1946
3 Tem Nieto 1969
23. Page 22Classification: Restricted
ORDER BY Clause
• Multiple fields
ORDER BY field1 SortingOrder, field2 SortingOrder, ...
• SortingOrder does not have to be same
• If field1 identical for two records, sorts by field2 in order specified
• SELECT * FROM Authors ORDER BY LastName, FirstName
AuthorID FirstName LastName YearBorn
1 Harvey Deitel 1946
2 Paul Deitel 1968
3 Tem Nieto 1969
24. Page 23Classification: Restricted
ORDER BY Clause
• Combining clauses
• SELECT * FROM Titles
WHERE Title LIKE '*How to Program'
ORDER BY Title ASC
• Multiple lines for readability
ISBN Title
Edition
Number
Year
Published
Publisher
ID
0-13-118043-6 C How to Program 1 1992 1
0-13-226119-7 C How to Program 2 1994 1
0-13-528910-6 C++ How to Program 2 1997 1
0-13-016143-8 Internet and World Wide Web How
to Program
1 1999 1
0-13-012507-5 Java How to Program 3 1999 1
0-13-899394-7 Java How to Program 2 1997 1
0-13-456955-5 Visual Basic 6 How to Program 1 1998 1
25. Page 24Classification: Restricted
Using INNER JOIN to Merge Data from Multiple Tables
• Merging data
• Combine multiple tables (join) by merging records
• SELECT * FROM Table1 INNER JOIN Table2 ON Table1.field =
Table2.field
• ON - "on condition that"
• Specifies fields to be compared for records to be merged
• Syntax
• If two tables have same field, use TableName.fieldName
• Can be used in any query to distinguish fields
• SELECT FirstName, LastName, ISBN
FROM Authors INNER JOIN AuthorISBN
ON Authors.AuthorID = AuthorISBN.AuthorID
ORDER BY LastName, FirstName
27. Page 26Classification: Restricted
SQL to Create a Table
CREATE TABLE Products
(
Product_Code CHAR(11) Description CHAR(40) Unit_Price
DECIMAL(10,2)
)
28. Page 27Classification: Restricted
SQL to Add Data to a Database
•Use the INSERT command to insert rows into the table
•Issue one command for each row of the table
INSERT INTO Products VALUES ('3554-0632-1', 'Hair dryer', 29.95)
29. Page 28Classification: Restricted
Inserting and Updating
• SQL statement for inserting data
INSERT INTO tableName ( columnName1, columnName2,... )
VALUES ( 'value1', 'value2', ... )
• Columns to be updated in comma-separated list
• Value for columns specified comma-separated list after VALUES
• Create INSERT INTO statement using JTextFields
109 String query = "INSERT INTO addresses (" +
110 "firstname, lastname, address, city, " +
30. Page 29Classification: Restricted
Reading, Inserting, and Updating
• Class UpdateRecord
• Event handler for Update button
• UPDATE SQL statement
UPDATE tableName SET columnName1 = 'value1', columnName2 =
'value2', ...
WHERE criteria
• Use ID as criteria
• Use method executeUpdate to update
264 String query = "UPDATE addresses SET " +
265 "firstname='" + fields.first.getText() +
266 "', lastname='" + fields.last.getText() +
267 "', address='" + fields.address.getText() +
33. Page 32Classification: Restricted
Basic Ingredients of JDBC
1.) Declare a database connection object.
2.) Load the JDBC/ODBC Driver class file.
3.) Make a database connection.
4.) Create a statement object.
5.) Execute the statement.
6.) Close the database connection.
34. Page 33Classification: Restricted
JDBC Driver Types
Driver Type Description
ODBC-JDBC Bridge Maps JDBC calls to ODBC driver
calls on the client.
Native API-Java Maps JDBC calls to native calls
on the client.
JDBC Network-All Java Maps JDBC calls to “network”
protocol, which calls native
methods on server.
Native Protocol-All Java Directly calls RDBMS from the
client machine.
35. Page 34Classification: Restricted
JDBC
Loading the JDBC Drivers
Loading the driver or drivers you want to use is very simple and involves
just one line of code. If, for example, you want to use the JDBC-ODBC
Bridge driver, the following code will load it:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Your driver documentation will give you the class name to use. For
instance, if the class name is jdbc.DriverXYZ , you would load the driver
with the following line of code:
Class.forName("jdbc.DriverXYZ");
You do not need to create an instance of a driver and register it with the
DriverManager because calling Class.forName will do that for you
automatically.
36. Page 35Classification: Restricted
Making a Database Connection
It just takes one statemente:
Connection con = DriverManager.getConnection(url,
"myLogin", "myPassword");
This step is also simple, with the hardest thing being what to supply for url .
If you are using the JDBC-ODBC Bridge driver, the JDBC URL will start with
jdbc:odbc: . The rest of the URL is generally your data source name or
database system. So, if you are using ODBC to access an ODBC data source
called " John, " for example, your JDBC URL could be jdbc:odbc:Fred . In
place of " myLogin " you put the name you use to log in to the DBMS; in
place of " myPassword " you put your password for the DBMS. So if you log
in to your DBMS with a login name of " Linda " and a password of " L8, "
just these two lines of code will establish a connection:
String url = "jdbc:odbc:John";
Connection con = DriverManager.getConnection(url, ”Linda", ”L8");
JDBC
37. Page 36Classification: Restricted
JDBC
Creating JDBC Statements
A Statement object is what sends your SQL statement to the DBMS.
You simply create a Statement object and then execute it
Statement stmt = con.createStatement();
At this point stmt exists, but it does not have an SQL statement to pass
on to the DBMS. We need to supply that to the method we use to
execute stmt . For example, in the following code fragment, we supply
executeUpdate with the SQL statement from the example above:
stmt.executeUpdate("CREATE TABLE MOVIES " +
"(MOV_NAME VARCHAR(32), SUP_ID INTEGER, PRICE FLOAT, " +
"SALES INTEGER, TOTAL INTEGER)");
If we made a string out of the SQL statement and assigned it to the
variable createTableMovies , we could have written the code in this
alternate form:
stmt.executeUpdate(createTableCoffees);
39. Page 38Classification: Restricted
Basic Ingredients of JDBC
// Declare a database connection object
Connection con = null;
// Load the Driver class file
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Make a connection to the ODBC datasource Movie Catalog
con = DriverManager.getConnection("jdbc:odbc:MovieCatalog",
"", "");
// Create the statement
Statement statement = con.createStatement();
// Use the created statement to SELECT the DATA
// FROM the Titles Table.
ResultSet rs = statement.executeQuery("SELECT * " +
"FROM Titles");
// Close the connection no matter what
con.close();
41. Page 40Classification: Restricted
Basic Ingredients of JDBC
Vector columnHeads = new Vector();
Vector rows = new Vector();
/ get column heads
ResultSetMetaData rsmd = rs.getMetaData();
System.out.println( "rsmd.getColumnCount() " + rsmd.getColumnCount() );
for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
columnHeads.addElement( rsmd.getColumnName( i ) );
// get row data
do {
rows.addElement( getNextRow( rs, rsmd ) );
} while ( rs.next() );
42. Page 41Classification: Restricted
Basic Ingredients of JDBC
// display table with ResultSet contents
table = new JTable( rows, columnHeads );
JScrollPane scroller = new JScrollPane( table );
getContentPane().add(scroller, BorderLayout.CENTER );
validate();
44. Page 43Classification: Restricted
Load a Driver
Loading the driver or drivers you want to use is very simple and involves just one line
of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following
code will load it:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Your driver documentation will give you the class name to use. For instance, if the
class name is jdbc.DriverXYZ , you would load the driver with the following line of
code:
Class.forName("jdbc.DriverXYZ");
You do not need to create an instance of a driver and register it with the
DriverManager because calling Class.forName will do that for you automatically. If
you were to create your own instance, you would be creating an unnecessary
duplicate, but it would do no harm.
When you have loaded a driver, it is available for making a connection with a DBMS.
45. Page 44Classification: Restricted
Make a Connection
The following line of code illustrates making a connection:
Connection con = DriverManager.getConnection(url,
"myLogin", "myPassword");
If you are using the JDBC-ODBC Bridge driver, the JDBC URL will start with
jdbc:odbc: . The rest of the URL is generally your data source name or
database system. So, if you are using ODBC to access an ODBC data source
called " Fred, " for example, your JDBC URL could be jdbc:odbc:Fred . In place
of " myLogin " you put the name you use to log in to the DBMS; in place of "
myPassword " you put your password for the DBMS. So if you log in to your
DBMS with a login name of " Fernanda " and a password of " J8, " just these
two lines of code will establish a connection:
String url = "jdbc:odbc:Fred";
Connection con = DriverManager.getConnection(url,
"Fernanda", "J8");
46. Page 45Classification: Restricted
Create a Statement
A Statement object is what sends your SQL statement to the DBMS. You
simply create a Statement object and then execute it, supplying the
appropriate execute method with the SQL statement you want to send. For a
SELECT statement, the method to use is executeQuery . For statements that
create or modify tables, the method to use is executeUpdate .
It takes an instance of an active connection to create a Statement object. In
the following example, we use our Connection object con to create the
Statement object stmt :
Statement stmt = con.createStatement();
47. Page 46Classification: Restricted
Execute a Statement
At this point stmt exists, but it does not have an SQL statement to pass on to the
DBMS. We need to supply that to the method we use to execute stmt . For
example, in the following code fragment, we supply executeUpdate with the SQL
statement from the example above:
stmt.executeUpdate("CREATE TABLE COFFEES " +
"(COF_NAME VARCHAR(32), SUP_ID INTEGER, PRICE FLOAT, " +
"SALES INTEGER, TOTAL INTEGER)");
49. Page 48Classification: Restricted
Retrieving Values from Result Sets
JDBC returns results in a ResultSet object, so we need to declare an instance of
the class ResultSet to hold our results. The following code demonstrates
declaring the ResultSet object rs and assigning the results of our earlier query to
it:
ResultSet rs = stmt.executeQuery( "SELECT * FROM emp“ );
50. Page 49Classification: Restricted
Using the Method next
The variable rs , which is an instance of ResultSet , contains the selected rows.
In order to access the names and prices, we will go to each row and retrieve the
values according to their types. The method next moves what is called a cursor
to the next row and makes that row (called the current row) the one upon
which we can operate. Since the cursor is initially positioned just above the first
row of a ResultSet object, the first call to the method next moves the cursor to
the first row and makes it the current row. Successive invocations of the method
next move the cursor down one row at a time from top to bottom. The JDBC
2.0 API allows backward movement of the cursor to specific positions and to
positions relative to the current row in addition to moving the cursor forward.
51. Page 50Classification: Restricted
Using the get Methods
Use the get method of the appropriate type to retrieve the value in each
column. For example, the first column in each row of rs is COF_NAME ,
which stores a value of SQL type VARCHAR . The method for retrieving a
value of SQL type VARCHAR is getString . The second column in each row
stores a value of SQL type FLOAT , and the method for retrieving values
of that type is getFloat . The following code accesses the values stored in
the current row of rs and prints a line with the name followed by three
spaces and the price. Each time the method next is invoked, the next
row becomes the current row, and the loop continues until there are no
more rows in rs .
52. Page 51Classification: Restricted
Example of Get Method
String query =
"SELECT COF_NAME, PRICE FROM COFFEES";
ResultSet rs = stmt.executeQuery(query);
while (rs.next())
{
String s = rs.getString("COF_NAME");
float n = rs.getFloat("PRICE");
System.out.println(s + " " + n);
}
56. Page 55Classification: Restricted
Using Prepared Statements
If you want to execute a Statement object many times, it will normally reduce
execution time to use a PreparedStatement object.
The main feature of a PreparedStatement object is that, unlike a Statement object,
it is given an SQL statement when it is created. The advantage to this is that in most
cases, this SQL statement will be sent to the DBMS right away, where it will be
compiled. As a result, the PreparedStatement object contains not just an SQL
statement, but an SQL statement that has been precompiled. This means that
when the PreparedStatement is executed, the DBMS can just run the
PreparedStatement 's SQL statement without having to compile it first.
Although PreparedStatement objects can be used for SQL statements with no
parameters, you will probably use them most often for SQL statements that take
parameters. The advantage of using SQL statements that take parameters is that
you can use the same statement and supply it with different values each time you
execute it. You will see an example of this in the following sections.
57. Page 56Classification: Restricted
Creating a PreparedStatement Object
As with Statement objects, you create PreparedStatement objects with a
Connection method. Using our open connection con from previous
examples, you might write code such as the following to create a
PreparedStatement object that takes two input parameters:
PreparedStatement updateSales = con.prepareStatement(
"UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
The variable updateSales now contains the SQL statement, "UPDATE
COFFEES SET SALES = ? WHERE COF_NAME LIKE ?" , which has also, in most
cases, been sent to the DBMS and been precompiled.
58. Page 57Classification: Restricted
Supplying Values for Prepared Statement Parameters
Using the PreparedStatement object updateSales from the previous example, the
following line of code sets the first question mark placeholder to a Java int with a
value of 75:
updateSales.setInt(1, 75);
As you might surmise from the example, the first argument given to a setXXX
method indicates which question mark placeholder is to be set, and the second
argument indicates the value to which it is to be set. The next example sets the
second placeholder parameter to the string " Colombian ":
updateSales.setString(2, "Colombian");