JDBC 1
JDBC 1
(JDBC)
Contents
• Data Base
• Database Schema
• A Brief Overview Of The JDBC Process
• JDBC Driver Types
• JDBC Packages
• Database Connection
• Creating, Inserting, Updating And Deleting Data In Database
Tables
• Result Set
• Metadata
Data Base & Database Schema
• Database is a large collection of related data that can be stored
and generally describes activities of an organization.
• A database management system (DBMS) is software for
defining, creating, manipulating and maintaining a database.
• Database Schema refers to the overall structure of a database.
• The description of a database is called the database schema,
which is specified during database design and is not expected to
change frequently
Cont …
STUDENT
• TEACHER
TeacherName TeacherId TeacherDepartment TeachingcourseId
Java Database Connectivity (JDBC)
• Java API for Database Connectivity
• JDBC is an application program interface (API) specification for
connecting programs written in Java to the data in popular databases
• JDBC is used for accessing databases from Java applications
• Java JDBC is a Java API to connect and execute query with the database.
JDBC API uses jdbc drivers to connect with the database.
• JDBC was developed by Sun Microsystems and JavaSoft
Database Connectivity History
Before APIs like JDBC and ODBC, database connectivity
was tedious:
• The driver converts JDBC method calls into native calls of the database API
• so this driver is also known as a Native-API driver
• The JDBC type 2 driver uses the libraries of the database which is available
at client side
• These drivers are typically provided by the database vendors.
• The vendor-specific driver must be installed on each client machine.
• If we change the Database, we have to change the native API, as it is
specific to a database
Type 3 Driver : Network-Protocol Driver(Pure Java driver for database
Middleware).
Cont…
java.sql package
•The first package is called java.sql and contains core JDBC classes and
interfaces of the JDBC API.
•These include the JDBC interfaces that provide the basics for connecting
to the DBMS and interacting with data stored in the DBMS
•This package include classes and interface to perform almost all JDBC
operation such as creating and executing SQL Queries.
classes and interface of java.sql package
classes/interface Description
java.sql.Connection creates a connection with specific database
java.sql.CallableStatement Execute stored procedures
java.sql.Driver create an instance of a driver with the DriverManager.
java.sql.DriverManager This class loads the database drivers.
java.sql.PreparedStatement Used to create and execute parameterized query.
java.sql.ResultSet It is an interface that provide methods to access the result
row-by-row.
java.sql.SQLException Encapsulate all JDBC related exception.
java.sql.Statement This interface is used to execute SQL statements
javax.sql package
•The JDBC driver must be loaded before the Java application can
connect to the DBMS.
•The Class.forName() method is used to load the JDBC driver
•Here forName() is a method of class Class.
•The driver is loaded by calling the Class.forName() method and
passing it the name of the driver
Class.forName("com.mysql.jdbc.Driver");
2. Creating a Connection to DataBase
•Once the driver is loaded, getConnection() method of DriverManager Class is
used to create a connection with the database.
•The Java application must connect to the DBMS using the
DriverManager.getConnection() method
Syntax:
getConnection(String url, String username, String password)
•url is the location of database.
• The DriverManager.getConnection() returns a Connection interface that is used
throughout the process to reference the database.
Example:
Connection con=
DriverManager.getConnection("jdbc:mysql://localhost/databasename","root","roo
3. Creating a statement object
•The next step after the JDBC driver is loaded and a connection is
successfully made with a particular database is to send an SQL query to
the DBMS for processing.
•The statement object is responsible to execute queries with the database.
•createStatement() method of Connection object is used create a
Statement object.
Example:
Statement stmt=con.createStatement();
4. Executing a SQL statement
•The methods of Statement object is used to execute a query and return a
ResultSet object that contains the response from the DBMS.
Methods statement object:
executeQuery() is used for SELECT statement.
executeUpdate() is used for create, alter or drop table.
execute() is used when multiple results may be returned
Example:
String query="create table employee1(empid varchar(20),empname
varchar(30),empsal varchar(20))";
stmt.executeUpdate(query);
5. Closing the connection
•The close()method of Connection interface is used to close the
connection.
Con.close()
Example
import java.sql.*;
class create1
{
public static void main(String rags[])throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost/IIICSE","root","root");
Statement stmt=con.createStatement();
String query="create table employee1(empid varchar(20),empname varchar(30),empsal
varchar(20))";
stmt.executeUpdate(query);
con.close();
}
}
Database Connection
•A Java application does not directly connect to a DBMS.
• Instead, the Java application connects with the JDBC driver that
is associated with the DBMS.
•However, before this connection is made, the JDBC driver must
be loaded and registered with the DriverManager.
•The purpose of loading and registering the JDBC driver is to bring
the JDBC driver into the Java Virtual Machine (JVM).
•The Class.forName() is used to load the JDBC driver.
•The Class.forName() throws a ClassNotFoundException if an error
occurs when loading the JDBC driver.
Cont …
•The connection to the database is established by using one of
three getConnection() methods of the DriverManager object.
•A Connection object is returned by the getConnection() method
if access is granted, otherwise the getConnection() method throws
an SQLException.
getConnection(String url)
getConnection(String url, Properties prop)
getConnection(String url, String user, String password)
Cont …
Example:
class create1
{
public static void main(String rags[])throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=
DriverManager.getConnection("jdbc:mysql://localhost/IIICSE","root","root");
}
Creating Table
import java.sql.*;
class create
{
public static void main(String rags[])throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/IIICSE","root","root");
Statement stmt=con.createStatement();
String query="create table employee(empid varchar(20) primary key,empname
varchar(30),empsal varchar(20))";
stmt.executeUpdate(query);
con.close();
}
}
Inserting data into Table
import java.sql.*;
class insertrow
{
public static void main(String rags[])throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/IIICSE","root","root");
Statement stmt=con.createStatement();
String query="insert into employee values(697,'ramireddy',59000)";
stmt.executeUpdate(query);
System.out.println("values inserted");
con.close();
}
}
Droping Tables
import java.sql.*;
class drop
{
public static void main(String rags[])throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/iiicse","root","root");
Statement stmt=con.createStatement();
String query="drop table student";
stmt.execute(query);
System.out.println("table is dropped");
con.close();
}
}
Updating Tables
import java.sql.*;
class update
{
public static void main(String rags[])throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/iiicse","root","root");
Statement stmt=con.createStatement();
String query="update employee set esal=300000 where eid=1";
stmt.executeUpdate(query);
System.out.println("updated");
con.close();
}
}
Deleting data from tables
import java.sql.*;
class delete
{
public static void main(String rags[])throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/iiicse","root","root");
Statement stmt=con.createStatement();
String query="delete from employee where eid=697";
stmt.executeUpdate(query);
System.out.println("deleted");
con.close();
}
}
ResultSet
•A ResultSet is a Java object that contains the results of an SQL query.
• In other words, it contains the rows that satisfy the conditions of the
query
•The executeQuery() method is used to send the query to the DBMS for
processing and returns a ResultSet object that contains data requested by
the query.
•The ResultSet object contains methods that are used to copy data from the
ResultSet into a Java variables for further processing.
• Data in a ResultSet object is logically organized into a virtual table
consisting of rows and columns.
•In addition to data, the ResultSet object also contains metadata, such as
column names, column size and column data type.
ResultSet
•The ResultSet uses a virtual cursor to point to a row of the virtual
table.
•The virtual cursor is positioned above the first row of data when
the ResultSet is returned by the executeQuery() method.
•The virtual cursor moved to the next row using the next()
method.
• next() method returns a boolean true if the row contains data,
otherwise a boolean false is returned, indicating that no
more rows exist in the ResultSet.
ResultSet
•Once the virtual cursor points to a row, the getXXX() method is
used to copy data from the row to a variable.
•For example, the getString() method is used to copy String data
from a column of the ResultSet.
• The getXXX() method requires one parameter, which is an
integer that represents the number of the column that contains
the data.
•For example, getString(1) copies the data from the first column
of the ResultSet.
Selecting data from tables
import java.sql.*;
class selectall
{
public static void main(String rags[])throws SQLException, ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection
("jdbc:mysql://localhost/iiicse","root","root");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from employee");
while(rs.next())
{
System.out.println(rs.getInt(1) +" "+rs.getString(2)+" "+rs.getInt(3));
}
con.close();
}}
Scrollable ResultSet
•Until the release of JDBC 2.1 API, the virtual cursor could only be moved
down the ResultSet object.
•But today the virtual cursor can be moved backwards or even positioned
at a specific row.
•The first() method moves the virtual cursor to the first row in the
ResultSet.
•The last() method positions the virtual cursor at the last row in the
ResultSet.
•The previous() method moves the virtual cursor to the previous row.
•The absolute() method positions the virtual cursor at the row number
specified by the integer passed as a parameter to the absolute() method.
•The getRow() method returns an integer that represents the number of
the current row in the ResultSet.
Scrollable ResultSet
•The Statement object that is created using the createStatement() of the
Connection object must be set up to handle a scrollable ResultSet by passing
the createStatement() method one of three constants.
• These constants are TYPE_FORWARD_ONLY,TYPE_SCROLL_INSENSITIVE,
and TYPE_SCROLL_SENSITIVE.
•The TYPE_FORWARD_ONLY constant restricts the virtual cursor to
downward movement.
• TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE constants
permit the virtual cursor to move in both directions.
Example on Scrollable Result Set
import java.sql.*;
class select
{
public static void main(String rags[])throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/iiicse","root","root");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from employee");
rs.absolute(2);
System.out.println(rs.getString(1) +" "+rs.getString(2)+" "+rs.getInt(3));
con.close();
}
}
Statement Objects
The statement object is responsible to execute queries with the database.
Any One of the three types of Statement objects is used to execute the
query.
Statement Object
•The Statement object is used whenever a Java application needs to
execute a query immediately without first having the query compiled.
•The statement object is responsible to execute static sql queries with the
database.
•createStatement() method of Connection object is used create a
Statement object.
Example:
Statement stmt=con.createStatement();
•The Statement interface provides three different methods for executing
SQL statements, executeQuery(), executeUpdate(), and execute().
•The method executeQuery(String sql) is designed for SELECT statements
Statement Object
•The method executeUpdate(String sql) is used to execute INSERT, UPDATE,
DELETE, CREATE and DROP statements.
•The return value of executeUpdate() is an integer indicating the number of
rows that were affected.
•The method execute(String sql) is used to execute statements that return
either result set or update count
PreparedStatement Object
•A prepared statement is used to execute the same SQL
statements repeatedly.
•Use when you plan to use the SQL statements many times.
•It is used to execute parameterized query.
•The query is constructed similar to queries but a question mark
is used as a placeholder for a value that is inserted into the
query after the query is compiled.
insert into emp values(?,?,?)
•It is the value that changes each time the query is executed.
PreparedStatement Object
stmt.setInt(1, empID);
Metadata
•Metadata is data about data.
•A Java application retrieves metadata about the database by
calling the getMetaData() method of the Connection object.
• The getMetaData() method returns a DatabaseMetaData object
that contains information about the database and its
components.
•The DatabaseMetaData interface have the information about
databases, tables, columns, indexes and other information
about the DBMS
Metadata
DatabaseMetaData object methods:
■ getDatabaseProductName() :Returns the product name of the database
■ getUserName() :Returns the user name
■ getURL() :Returns the URL of the database
■ getSchemas(): Returns all the schema names available in this database
■ getPrimaryKeys() :Returns primary keys
■ getTables() :Returns names of tables in the database
ResultSet Metadata
•Two types of metadata can be retrieved from the DBMS: metadata that
describes the database and metadata that describes the ResultSet.
•Metadata that describes the ResultSet is retrieved by calling the
getMetaData() method of the ResultSet
•Once the ResultSet metadata is retrieved, the Java application can call
methods of the ResultSetMetaData object to retrieve specific kinds of
metadata.
The more commonly called methods are
■ getColumnCount():Returns the number of columns contained in the
ResultSet
■ getColumnName(int number): Returns the name of the column specified
by the
column number
■ getColumnType(int number): Returns the data type of the column
Example:
import java.sql.*;
class metadata
{
public static void main(String rags[])throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/IIICSE","root","root");
DatabaseMetaData meta=con.getMetaData();
String uname=meta.getUserName();
String pname=meta.getDatabaseProductName();
String url=meta.getURL();
System.out.println(uname);
System.out.println(url);
System.out.println(pname);
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from employee");
ResultSetMetaData rsmd=rs.getMetaData();
System.out.println("Total columns: "+rsmd.getColumnCount());
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));
con.close();
}
}