Professional Documents
Culture Documents
JDBC
Introduction
The success of any business depends on the
information and data assets it possesses.
Therefore it is very important for a business to have a
system for storing and retrieving data.
Though files are used for storing data, they are highly
inefficient in many respects like the amount of data
that can be stored, retrieving the data and many
more.
In order for the businesses to be competent, they
need sophisticated systems for storing complex and
heavy volume of data and at the same time retrieve
the data faster enough to process the data. One such
systems are the so called Databases.
Database Basics
Databases store the data in the form of tables with
each table containing several records of data.
Databases are broadly categorized into two types as
listed below:
Single table databases and
Multi table or relational databases.
A single table databases doesnt mean that they have
just one table. It will have several tables of data and
all the tables are independent of each other.
The main drawback with these databases is the lack of
flexibility while retrieving the data.
On the other hand in multi table databases, two or
more tables are related with other. This feature offers
more flexibility and power to retrieve the data.
These databases are therefore called as relational
databases. Most of the modern enterprises use
Name
SSN
Age
Countr
John
123456
47
y
USA
Smith
7
343534
21
Canada
5
Table:Customer
The above table shows customers table that has two
records of data. A typical database will have n
number tables with each having n number of records.
Name
John
SSN
12345
Age
Countr
47
y
USA
67
SSN
AddressLine
City
Smith
34353AddressLin
21
Canad
1
e2
45
a
123456 Apt # 20
1111 S St
LA
7
343534 Apt #2345
2222 N St
5
Table:Address
Detroit
Table:Custo
mer
State
CA
MI
Creating a table
Lets create a table named Customers to store
customer data like firstname, lastname, ssn, age,
city, state, and country as shown below:
FirstNam LastNam SSN
e
Age
City
State
Count
ry
Description
Used for storing text
NUMERIC
data
Used
DATE
numbers
Used for storing dates
for
storing
me
John
123456
Age
20
City
Vegas
State
Countr
CA
y
USA
WHERE
COLUMN 1 NAME = VALUE 1 AND
COLUMN 2 NAME = VALUE 2 ..
Lets say we want to change the last name to Roberts
and first name to Joe whose SSN is 123456. The
update query will be,
UPDATE CUSTOMERS SET
FirstName = Joe, LastName = Roberts
WHERE SSN = 123456
AB3456
Perl Scripting
McGraw
YZ6789
Core Java
Table: Books
Author
ISBN
Country
Smith
AB3456
Germany
John
YZ6789
Australia
Table: Authors
JDBC
JDBC stands for Java Database Connectivity which
is a technology that allows Java applications to,
1. Interact with relational databases
2. Execute SQL queries against the databases
. To better understand JDBC technology, look at the
following figure:
Database Drivers
A driver is not a hardware device. Its a software
program that could be written in any language.
Every database will have its own driver program.
Given a driver program of a particular database,
the challenge is how to use it to talk with
database. To understand this, we need to know
the different types of drivers.
There are basically 4 different types of database
drivers as described below:
3. Intermediate Database
access Driver Server
This is also known as Type-3 driver.
If you look at the Type-2 driver configuration, we
only access one database at a time.
However there will be situations where multiple
Java programs need to access to multiple
databases. This is where Type-3 driver is used.
It acts as a middleware for the applications to
access several databases.
The Type-3 configuration internally may use Type2 configuration to connect to database.
JDBC API
import java.sql.Connection;
import java.sql.DriverManager;
public class ConnectionTest {
public static void main(String args[]) {
try {
// Step 1: Load the Driver
Class.forName("com.mysql.jdbc.Driver");
// Step 2: Get the connection by passing the URL
String url = "jdbc:mysql://localhost:3306/MyDB";
Connection con =
DriverManager.getConnection(url,"root","12345");
System.out.println(con);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Creating Table
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class CreatingTable {
public static void main(String args[]) throws Exception
{
createTable();
}
private static void createTable() throws Exception {
String sql = "CREATE TABLE CUSTOMERS" + "(" +
"FIRSTNAME VARCHAR(50),"+ "MIDDLENAME
VARCHAR(2)," + "LASTNAME VARCHAR(50)," + "AGE
NUMERIC(2)," + "SSN NUMERIC(10)," + "CITY
VARCHAR(32),"+ "STATE VARCHAR(2)," + "COUNTRY
VARCHAR(40)" + ")";
Inserting Data
import java.io.*;
import java.sql.*;
import java.util.StringTokenizer;
public class InsertingData {
public static void main(String args[]) throws
Exception {
String sql = "INSERT INTO CUSTOMERS
VALUES(" + " ' " + firstName + " ' , " + " ' " +
middleName + " ' , " + " ' " + lastName + " ' , " +
age + " , " + ssn + " , " + " ' " + city + " ' , " + " ' "
+ state + " ' , " + " ' " + country + " ')";
// Pass the sql to JDBC method
insertCustomer(sql);
import java.sql.*;
public class ReadingData {
static Connection con = null;
static Statement stmt = null;
static ResultSet rs = null;
public static void main(String args[]) throws Exception
{
readData();
}
private static void readData() throws Exception {
// Create the SQL
String sql = "SELECT * FROM CUSTOMERS";
// Get the connection using our utils.
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/MyDB";
Connection con = DriverManager.getConnection(url,
"root", "12345");
if (con != null) {
// Create statement from connection
stmt = con.createStatement();
// Execute the statement by passing the sql.
rs = stmt.executeQuery(sql);
// Iterate over all the returned records
while (rs.next()) {
String firstName = rs.getString(1);
String middleName = rs.getString(2);
String lastName = rs.getString(3);
int age = rs.getInt(4);
int ssn = rs.getInt(5);
String city = rs.getString(6);
String state = rs.getString(7);
String country = rs.getString(8);
import java.sql.*;
public class ReadingData2 {
static Connection con = null;
static Statement stmt = null;
static ResultSet rs = null;
public static void main(String args[]) throws Exception {
readData();
}
private static void readData() throws Exception {
// Create the SQL
String sql = "SELECT firstname FROM CUSTOMERS";
// Get the connection using our utils.
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/MyDB";
Connection con = DriverManager.getConnection(url, "root",
"12345");
if (con != null) {
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
String firstName = rs.getString(1);
System.out.println("Firstname::"+firstName);
}
} else {
System.out.println("Unable to get the connection");
}
}
}
UPDATE
import java.sql.*;
import javax.swing.JOptionPane;
if (con != null) {
stmt = con.createStatement();
int result=stmt.executeUpdate(sql);
if(result!=-1){
JOptionPane.showMessageDialog(null, "Update
record Successfully");
}else{
JOptionPane.showMessageDialog(null, "Failed to
update record ");
}
} else {
System.out.println("Unable to get the
connection");
}
}
}
DELETE
import java.sql.*;
import javax.swing.JOptionPane;
public class DeleteRecord {
static Connection con = null;
static Statement stmt = null;
if (con != null) {
stmt = con.createStatement();
int result=stmt.executeUpdate(sql);
if(result!=-1){
System.out.println("deleted");
//JOptionPane.showMessageDialog(null,
"Delete record Successfully");
}else{
JOptionPane.showMessageDialog(null, "Failed
to Delete record ");
}
} else {
System.out.println("Unable to get the
connection");
}
}
PreparedStatement
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class PrepareStatementDemo {
static Connection con = null;
static PreparedStatement pstmt = null;
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/MyDB";
con =
DriverManager.getConnection(url,"root","12345");
String query = "INSERT INTO CUSTOMERS values
(?,?,?,?,?,?,?,?)";
pstmt = con.prepareStatement(query);
pstmt.setString(1, "harry");
pstmt.setString(2, "p");
pstmt.setString(3, "porter");
pstmt.setInt(4, 20);
pstmt.setInt(5, 123);
pstmt.setString(6, "abas");
pstmt.setString(7, "adsfasdf");
pstmt.setString(8, "FADSFA");
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Connection Pooling
In all the programs we wrote thus far, there is one
thing that we are repeatedly doing all the times.
Opening a connection at the beginning and closing the
connection at the end when everything is done.
There are two major problems that hunt us when we
write database programs.
Problem 1: Usually, every database has limited
number of connections. Lets say a database supports
only 10 connections, and if your program doesn't close
the connection every time it ran, the 11th time you
run, database will refuse to give you a connection. If
you don't close a connection after using it, from
database point of view somebody is still using the
connection, and it will not reuse this connection until
the connection is closed. You need to shutdown the
database and restart it to release all the connections
which is not good.