You are on page 1of 62

Databases and

Database Connection
in Java
DEFINITIONS

 Database: organized collection of logically related data


 Data: stored representations of meaningful objects and events
 Structured: numbers, text, dates
 Unstructured: images, video, documents
 Information: data processed to increase knowledge in the person using the
data
 Metadata: data that describes the properties and context of user data
 Database Management Systems: Used to create, maintain, and access databases
(used by professional programmers)
Ex: MySQL – Oracle – Access – Sybase –Microsoft SQL
2
APPLICATION PROGRAMS

 Application programs are build


on the top of DBMS for
customers to update and use
database.
 Application program can
access multiple
database systems.
APPLICATION PROGRAMS
WHAT IS A DATABASE?
 A database typically consists of:
 Tables: Collection of related records
 Fields (columns): Single category of data to be stored in a database (name,
telephone number, etc.)
 Records (rows): Collection of related fields in a database (all the fields for one
customer, for example)
Field

Table

Record
COURSE INFORMATION TABLE
STUDENT TABLE
RELATIONAL DATABASE

 A relation is a table that consists of non-duplicated rows.


 Relational database: Data from several tables is tied together (related)
using a field that the tables have in common
INTEGRITY CONSTRAINT
1. Domain constraint – the possible values for the
attribute
2. Primary key constrain – Specific field that
uniquely identifies the records in that table
 Used in a relational database to relate tables together
 Must be unique and a field that doesn’t change
3. Foreign key constrain – Attribute(s) that identify
the relation between tables
EXERCISE 1:WHAT IS THE PRIMARY KEY?
EXERCISE 2:WHAT IS THE PRIMARY KEY?
DATA CONCEPTS AND CHARACTERISTICS
 Entity relationships: Describe an association between two or more entities
 One-to-one (1:1) entity relationships (not common)
 e.g. each store has a single manager, each person has a driver licenses
DATA CONCEPTS AND CHARACTERISTICS
 Entity relationships: Describe an association between two or more entities
 One-to-many (1:M) entity relationships (most common)
 e.g. a supplier supplies more than one product to a company
DATA CONCEPTS AND CHARACTERISTICS
 Entity relationships: Describe an association between two or more
entities
 Many-to-many (M:M) entity relationships (requires a third table to tie the tables
together)
 e.g. an order can contain multiple products and a product can appear on multiple orders
EXERCISE 3:WHAT IS THE TYPE OF RELATIONSHIP?
DATA CONCEPTS AND CHARACTERISTICS
 Data definition:The process of describing the properties of data to be included in a database table
 During data definition, each field is assigned:
 Name (must be unique within the table)
 Data type (such as Text, Number, Currency, Date/Time)
 Description (optional description of the field)
 Properties (field size, format of the field, allowable range, if field is required, etc.)
 Finished specifications
for a table become
the table structure
THE RELATIONAL DATABASE MODEL
 Retrieving information from database
 Query: A request to see information from a database that matches
specific criteria
 Specifies which records should be retrieved by specifying criteria
 Can specify the fields to be displayed
 Many programs have wizards or other tools to make it easy to create a query
 Must be designed to extract information as efficiently as possible
 Queries are saved so they can be retrieved again when needed; proper results
are displayed each time the query is run
Exercise 4: What is the title of the courses
registered by the student whose first name is
Jacob and last name is smith?
SQL
 To access or write applications for database systems, you need to use
the Structured Query Language (SQL).
 SQL is the universal language for accessing relational database systems.
 Application programs may allow users to access database without
directly using SQL, but these applications themselves must use SQL to
access the database.
 SQL statements are used to create tables, insert record, update records,
query database, delete records delete tables,………
 SQL can be used on MySQL, Oracle, IBM DB2, MS Access , .. etc
CREATING DATABASE

 create database <Database name>;


Ex: create database javabook;

 Use <Database name>; Ex: Use javabook;


CREATING TABLE

Create table <table name> (


field1_name Data_type(size) constraint default_value,
.
.

[primary key (field, field,….)]


[foreign key (field) references table_name (field)]
);
EXAMPLE 1

create table Course (


courseId char(5),
subjectId char(4) not null,
courseNumber integer,
title varchar(50) not null,
numOfCredits integer,
primary key (courseId)
);
EXAMPLE 1

create table Course ( constraint


courseId char(5),
Data_types
subjectId char(4) not null,
courseNumber integer, char(n) : field consists of exactly n
title varchar(50) not null, characters
numOfCredits integer, varchar(n): variant length string with
primary key (courseId) maximum n character
integer: integer number
); date: Date
float : Decimal number
DATA TYPES
EXAMPLE 2

create table Student (


ssn char(9),
firstName varchar(25),
mi char(1),
lastName varchar(25), birthDate date,
street varchar(25),
phone char(11),
zipCode char(5), deptId char(4),
primary key (ssn)
);
EXAMPLE 3

create table Enrollment (


ssn char(9),
courseId char(5),
dateRegistered date,
grade char(1),
primary key (ssn, courseId),
foreign key (ssn) references Student(ssn),
foreign key (courseId) references Course(courseId)
);
DATA
Data Manipulation Language
Is a part of sql that responsible for working on data of the database
tables
1- Inserting data into table[s].
2- Updating data for specific table
3- Deleting data from table
4- Retrieve (selecting) data from table[s]
INSERT DATA INTO TABLE

insert into tableName [(column1, column2, ..., column)]


values (value1, value2, ..., valuen);
Ex:
insert into Course (courseId, subjectId, courseNumber, title,
numOfCredits)
values ('11113', 'CSCI', '3720', 'Database Systems', 3);
MODIFY TABLE

update tableName
set column1 = newValue1 [, column2 = newValue2, ...] [where condition];
 Ex:
update Course
set numOfCredits = 4
where title = 'Database Systems’;

What will happen if the where statement does not exists?


DELETE RECORD FROM TABLE
delete from tableName
[where condition];

 Ex:
delete from Course
where title = 'Database Systems';

What will happen if the where statement does not exists?


 Delete all records from the table
SIMPLE QUERIES
select column-list
from table-list
[where condition];

 Ex: Select all students in CS department


select firstName, mi, lastName
from Student
where deptId = 'CS';
COMPARISON AND BOOLEAN OPERATORS
EXERCISE

 Get the names of the students who are in the CS dept and live in the
ZIP code 31411.

select firstName, mi, lastName


from Student
where deptId = 'CS' and zipCode = '31411';
NOTE

 To select all the attributes from a table, you don’t have to list all the
attribute names in the select clause. Instead, you can just use an asterisk
(*), which stands for all the attributes.
 Ex:
select *
from Student
where deptId = 'CS' and zipCode = '31411';
QUERY STATEMENTS

 v between v1 and v2 is equivalent to v >= v1 and v <= v2

 Ex:
select ssn
from Enrollment
where grade between 'A' and 'C';
QUERY STATEMENTS

 a like operator that can be used for pattern matching.


 s like p or s not like p
 % → matches zero or more characters
 _ (underscore) → matches any single character
 Ex: lastName like '_mi%' ➔ matches any string whose second and third
letters are m and I
 Ex: lastName not like '_mi%' ➔ excludes any string whose second and
third letters are m and i.
QUERY STATEMENTS

 distinct keyword, which can be used to eliminate duplicate tuples in the


result.
 Ex:
select distinct subjectId as "Subject ID“
from Course;
EXAMPLE: Mysql database
JOINING TABLES

 Often you need to get information from multiple tables.


Where Table1.field_name = Table2.field_name
 Example:
List the courses taken by the student Jacob Smith.To solve this query, you need
to join tables Student and Enrollment

select distinct lastName, firstName, courseId


from Student, Enrollment
where Student.ssn = Enrollment.ssn and
lastName = 'Smith' and firstName = 'Jacob';
EXERCISES: Try to write the select statement for the following

 List all CSCI courses with at least four credit hours.


 List all students whose last names contain the letter e two times.
 List all students whose birthdays are null.
 List all students who take Math courses.
JDBC
 JDBC is the Java API for accessing relational database.
 Using the JDBC API, applications written in the Java programming language
can:
1. execute SQL statements
2. retrieve results
3. present data in a user-friendly interface
4. propagate changes back to the database.
 The JDBC API can also be used to interact with multiple data sources
in a distributed, heterogeneous environment.
RELATION BETWEEN JAVA PROGRAMS AND RELATIONAL DATABASES
The JDBC Interfaces

Loading drivers

Establishing connections

Creating and executing


statements

Processing ResultSet

44
The JDBC Interfaces

▪ Package java.sql consists of classes and interfaces for


1- establishing connections with databases,
2- sending SQL statements to databases,
3- processing the results of the SQL statements, and
4- obtaining database metadata.
▪ Four key interfaces are needed to develop any database:
Driver, Connection, Statement, and ResultSet.
45
STEPS TAKEN BY THE JAVA PROGRAM TO ACCESS DATABASE

1. Loading driver
2. Establishing connection
3. Creating statement
4. Executing statement
5. Processing result set
6. Closing the connection
1- LOADING DRIVER
 An appropriate driver must be loaded using the statement shown below before connecting to
a database. Class.forName("JDBCDriverClass");
 Class Class<T> has a method named forName() that used to
Load the Class object associated with the class or interface with the given string name
 A driver is a concrete class that implements the java.sql.Driver interface.
 JDBC Drivers for each different database

JDBC drivers are database specific and are normally provided by the database vendors.
1- LOADING DRIVER(Cont.)
Statement to load a driver:
Class.forName("JDBCDriverClass");
A driver is a class. For example:

Database Driver Class Source


Access sun.jdbc.odbc.JdbcOdbcDriver Already in JDK7
MySQL com.mysql.jdbc.Driver mysqljdbc.jar
Oracle oracle.jdbc.driver.OracleDriver ojdbc6.jar
.. ……… …..
1- LOADING DRIVER(Cont.)
try{
//Load Driver for MS Access
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//Load Driver for MySQL
Class.forName("com.mysql.jdbc.Driver");
//Load Driver for Oracle
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch (ClassNotFoundException ex){
System.out.println("DataBase driver can not be loaded");
return;
}
Try-catch keywords: is used for exception handling
To prevent runtime error (because the driver may be not connected well)
1- LOADING DRIVER(Cont.)

The driver must be


downloaded and attached
to the netbeans project as
follows
2- ESTABLISH CONNECTION
 Connect to the database
 Syntax:
Connection connection = DriverManager.getConnection(databaseURL);
where databaseURL is the identifier of the database on the Internet.
 DriverManager class: located in package java.sql and contains two
overloaded methods for getting connection
static Connection getConnection(String url) throws SQLException
establish a connection to the given database URL.
static Connection getConnection(String url, String user, String password) throws SQLException
establish a connection to the given database URL.
2- ESTABLISH CONNECTION (Cont.)

 Connect to the database


 Syntax:
Connection connection = DriverManager.getConnection(databaseURL);
 JDBC URL
2- ESTABLISH CONNECTION (Cont.)
Connection connection = DriverManager.getConnection(databaseURL);

Examples:
For Access:
Connection connection =
DriverManager.getConnection("jdbc:odbc:ExampleMDBDataSource");
For MySQL:
Connection connection = DriverManager.getConnection
("jdbc:mysql://localhost/test“,"scott", "tiger");
For Oracle:
Connection connection =
DriverManager.getConnection("jdbc:oracle:thin:@liang.armstrong.edu:1521:orcl",
"scott", "tiger");
For MySql Database
Setting up MySql Databases server

XAMPP is a completely free, easy to install Apache web server including


MySQL, PHP, and Perl
https://www.apachefriends.org/index.html

HeidiSQL is a powerful and easy client for MySQL and MSSQL. Open
source and completely free to use.
EXERCISE: Review from previous slides

 Suppose a data source named ExampleMDBDataSource has been created for


an Access database, how to establish connection?
 Answer
Connection connection = DriverManager.getConnection ("jdbc:odbc:ExampleMDBDataSource");

 Suppose a data source named javabook has been created in local host MySQL
with username scott and password tiger, how to establish connection?
 Answer
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost/javabook", "scott", "tiger");
3- CREATING STATEMENTS

 A cable linking the program to a database, it played as a card that deliver SQL
statements for execution by the database.
 Connection Interface: located in package java.sql and contains a method
createStatement() that create Statement object for sending SQL
statements to the database.
public Statement createStatement() throws SQLException

The code:
Statement statement = connection.createStatement();
4- EXECUTING STATEMENTS
 Statement Interface: located in package java.sql and contains a two
methods named executeUpdate() and executeQuery(), which take the sql
command as String that will be executed on database.
public int executeUpdate(String sql) throws SQLException
public ResultSet executeQuery(String sql) throws SQLException
 Update statements (Runs the given SQL statement, which can be an INSERT, UPDATE, DELETE)
statement.executeUpdate ("create table Temp (col1 char(5), col2
char(5))");
 Execute query
ResultSet resultSet = statement.executeQuery ("select firstName, mi,
lastName from Student where lastName = 'Smith' ");
4- EXECUTING STATEMENTS(Cont.)
Creating statement:
Statement statement = connection.createStatement();

Executing statement (for update, delete, insert):


statement.executeUpdate("create table Temp (col1 char(5), col2 char(5))");

Executing statement (for select):


// Select the columns from the Student table
ResultSet resultSet = statement.executeQuery("select firstName, mi,
lastName from Student where lastName “ + " = 'Smith'");
5- PROCESSING RESULT SET
 Afetr executing The Select statement, a table of data were retrieved from the
database, the interface ResultSet process the returned table line-by-line, and
decompose it into several blocks
 ResultSet Interface: located in package java.sql and contains a several methods like
getString(), getInt(), getDouble(),….,etc.
 The ResultSet maintains a table whose current row can be retrieved by using the
following methods.
public String getString(int columnIndex) throws SQLException
Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java
programming language. First column has index=1;
public String getString(String columnLabel) throws SQLException
Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java
programming language.

public int getInt(String columnLabel) throws SQLException

public boolean next() throws SQLException


Moves the cursor froward one row from its current position
5- PROCESSING RESULT SET
Executing statement (for select):
// Select the columns from the Student table
ResultSet resultSet = stmt.executeQuery("select firstName, mi, lastName from Student
where lastName " + " = 'Smith'");

Processing ResultSet (for select):


// Iterate through the result and print the student names
while (resultSet.next())
System.out.println(resultSet.getString(1) + “\t" +
resultSet.getString(2) + ".\t " +
resultSet.getString(3) );

 getString(1) => methods for retrieving column values from the


table
6- CLOSING THE CONNECTION

 connection.close();
EXAMPLE
import java.sql.*;
public class SimpleJdbc {
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection ("jdbc:mysql://localhost/javabook" , "scott", "tiger");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery ("select firstName, mi, lastName from Student where
lastName = 'Smith'");
while (resultSet.next())
System.out.println(resultSet.getString(1) + "\t" + resultSet.getString(2) + "\t" + resultSet.getString(3));
connection.close();
}
catch(Exception ex){
System.out.println(ex);
}
}
}

You might also like