Lecture Notes of Java Java Database Connectivity (JDBC)
Lecture Notes of Java Java Database Connectivity (JDBC)
Java application calls the JDBC library. JDBC loads a driver which talks
to the database. We can change database engines without changing
database code.
Note: You can use ODBC Driver to connect with MS-Access, SQL
Server, Dbase and Foxpro. In order to do this, you need to define first
ODBC name through ODBC Data source control, which is present in
control panel.
3
Step
2:
Define
Connection
through
DriverManager
class
The JDBC DriverManager class defines objects which can connect Java
applications to a JDBC driver. DriverManager is considered the
backbone of JDBC architecture.
DriverManager class manages the JDBC drivers that are installed on
the system. Its getConnection() method is used to establish a
connection to a database.
It uses a username, password, and a jdbc url to establish a connection
to the database and returns a connection object.
A jdbc Connection represents a session/connection with a specific
database. Within the context of a Connection, SQL, PL/SQL statements
are executed and results are returned.
An application can have one or more connections with a single
database, or it can have many connections with different databases.
A Connection object provides metadata i.e. information about the
database, tables, and fields. It also contains methods to deal with
transactions.
import java.sql.*;
public class JDBCDemo {
public static void main( String[] args ) {
try {
// Connect to the database
Class.forName("jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:university";
Connection con = DriverManager.getConnection(url);
// Execute the SQL statement
Statement stmt = con.createStatement();
ResultSet resultSet = stmt.executeQuery("SELECT * from Faculty");
System.out.println("Faculty Code Name Designation!");
// Loop thru all the rows
while( resultSet.next() ) {
String code = resultSet.getString( "Faculty_code" );
System.out.print( code );
String name = resultSet.getString( "Faculty_Name" );
System.out.print( name );
String desg = resultSet.getString( "Designation" );
System.out.println( desg );
}
stmt.close();
}
catch( Exception e ) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
Java Type
MySQL Type
Java Type
CHAR
String
FLOAT
Double
VARCHAR
String
DOUBLE
Double
LONGVARCHAR
String
BINARY
byte []
NUMERIC
java.math.BigDecimal VARBINARY
DECIMAL
BIT
boolean
DATE
java.sql.Date
TINYINT
byte
TIME
java.sql.Time
SMALLINT
short
TIMESTAMP
java.sql.Tiimestamp
INTEGER
int
BIGINT
Long
BIGINT
long
REAL
float
byte []
stores the data in the form of tables. So, we can view and use the
same database in many different ways.
Information: Please find this program in a file name
CreateDatabase.java.
Description of program:
Firstly this program establishes the connection with MySQL database
and takes a database name as its input in the database query and only
after that it will create a new database and show a message "1 row(s)
affected" otherwise, it displays "SQL statement is not executed!".
Description of code:
CREATE DATABASE db_name;
Above code is used for creating a new database. It takes a database
name and then a new database is created by that name.
10
Description of code:
Statement:
It is a interface. Statement object executes the SQL statement and
returns the result it produces.
createStatement():
It is a method of Connection interface, which returns Statement object.
This method will compile again and again whenever the program runs.
CREATE TABLE table_name(field_name):
An appropriate code used for creating a table with given field name.
executeUpdate(String table):
This
method
also
executes SQL statement
that
may
be INSERT, UPDATE OR DELETE statement are used in the code. It
takes string types parameters for SQL statement. It returns int.
delete get deletes then we will print the message "Table Deletion
process is completely successfully!", otherwise it will display " Table is
not exists!".
DROP TABLE table_name:
Above code is used for deleting any table from a given database.
an
interface
that
12
provides
getter
methods
"1 row affected" but if any problems comes while inserting the data in
the table then it will displays the message "SQL statement is not
executed!".
Information: Please find this program in a file name
InsertValues.java.
INSERT table_name VALUES(field_values):
Above code is used, when you want to insert values in the database
table with appropriate value.
14
This
method
executes
and
returns
database in the query and the rows will be counted and the result will
be displayed. If any exception is thrown then it will show "SQL
statement is not executed!"
Description of code:
SELECT COUNT(*) FROM table_name;
This code is used to count the rows of given table. table_name: It is a
name of the table of which we want to see the rows.
Please
find
this
program
in
file
name
Columename.java.
Description of program:
Create a class ColumnName. The name of the class should be such
that the other person can easily understand what this program is going
to do. Strictly follow the naming conventions of java. Now declare a
static
method
inside
which
creates
the
connection
with MySQL database through the JDBC driver. After establishing the
16
connection then you get all columns name and number of columns of
specified table with the help of some APIs and methods.
ResultSetMetaData:
This is an interface of java.sql package that can be used for getting
information
about
types
and
properties
of
columns
in
a ResultSet object.
getColumnCount():
Above method retrieves number of columns (integer types data) in
the ResultSet object.
getColumnName(int column):
This
method
returns
columns
name
(string
type
data)
Firstly we need to create a connection with the help of JDBC driver for
connecting to the MySQLdatabase. Remember, in this program we are
going to add columns to an existing database table. After establishing
the connection, it takes table name, column name and it's data type
and at last add a new column in the table. If the column gets inserted
or added in the table then it shows "Query OK, n rows affected"
otherwise it will displays a message "Table or column or data type is
not found!".
Information:
Please
find
this
program
in
file
name
AddColume.java.
ALTER TABLE
Above code is used for adding a new column in the database table and
takes appropriate attributes:
table_name: This is a table name in which you want to add a new
column name.
col_name: It is a name of the column that you want to add in a table.
data_type: This is a data type of new column.
Please
find
this
program
in
file
name
SumColume.java.
Description of program:
In the program the first
connection with MySQL database by using the JDBC driver. When the
connection has been established pass the table name and name of that
column of which we want to calculate the sum. If the statement gets
processed then it shows the sum of the particular column else it will
displays a message "SQL statement is not executed!".
SELECT SUM(col_name)
FROM table_name:
Information:
Please
find
this
program
in
file
name
DeleteAllRows.java.
Description of program:
This program establishes the connection between the MySQL database
and java file with the help of a jdbc driver. After that deletes all rows
by the SQL statement and shows a message "All rows are completely
deleted!". If SQL statement is not executed then displays "SQL
statement is not executed!".
Delete from table.
20
Information:
Please
find
this
program
in
file
name
DeleteSpecificRow.java.
Description of program:
Firstly, in this program we are going to establish the connection by
using MySQL database. After establishing the connection we are going
to delete a specific row from the table. If the row get deletes
successfully then it will shows an appropriate message: "Row is
deleted.". If the row doesn't gets deleted then displays a message:
"Row is not deleted". If there arises any problem while establishing the
connection or there doesn't exist the table by that name or there is no
data in the table then the exception will be thrown that "SQL
statement is not executed". If any problems occurs while making
connection
then
system
displays
message
with
the
help
of java.lang.ClassNotFoundExceptionexception.
Description of code:
DELETE FROM employee6 WHERE Emp_code = '1':
Above
code
deletes
the
record
in
which
This
is
table
name
of
specific
database.
21
Join tables
Consider a case, where there is too many records and tables in a
database. Now to retrieve a particular row from a table or database is
a very time consuming. So, what the alternative to that, divide the
table in more than one table. In this section, we are going to see how
to join two or more tables in a specific database. For this you need to
have two or more table in the database. If two or more tables are
available in the database then Join operation is performed otherwise
not. Firstly, it is important to know about the join operation. Join
operation provides the facility to combine records between two or
more tables. It relates one table to another. Joining is the type of
query for retrieving data two or more table in specific database. You
can join the tables various types like: Natural join, Natural left join,
Natural right join and so on. Here we are providing you an example
with code that joins two tables through theNATURAL JOIN. Brief
information given below:
Join: A join provides the facility to connect two tables are merged to
each other according to field that is common and creates a new virtual
table.
NATURAL JOIN: It is a type of join that retrieves data within specified
tables to specific field is matched.
NATURAL LEFT JOIN: In this operation both tables are merged to each
other according to common fields but the priority is given to the first
table in database.
22
NATURAL RIGHT JOIN: It also same as Natural left join but it retrieves
the data from the second table in the database.
Information:
Please
find
this
program
in
file
name
NatJoinTable.java.
Description of program:
First
of
all,
this
program
establishes
the
connection
with MySQL database through the JDBC driver. After establishing the
connection the NATURAL JOIN operation is performed within two tables
say: employee and Emp_sal. The employee table holds the Emp_ed
and Emp_name fields and Emp_sal table contains the Emp_name and
Emp_sal. We are making use of the emp_name to join the tables.
Description of code:
SELECT *FROM employee NATURAL JOIN Emp_sal:
This code is used to show all fields that matches in the both tables on
the basis of Emp_name field.
23