Unit 8 JDBC
Unit 8 JDBC
Unit 8 JDBC
com
Unit-8/ Java Programming - II
Database Basics
A database as the name suggests is a sophisticated system for storing the data. 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 doesn’t 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 relational databases.
A typical database will have ‘n’ number tables with each having ‘n’ number of records.
A relational database can store the data in several tables that are related with each other
as shown below:
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
If you notice the above tables, they are related with each other by the common column SSN. The
two tables together represent the customer information. To pull the customer information, we
need to pull the data from both the tables based on the matching SSN.
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
Time with TIME WITH TIME It is exactly same as time but also
time zone ZONE store an offset from UTC of the
time specified.
Timestamp TIMESTAMP with It is same as timestamp but also
with time TIME ZONE stores an offset from UTC of the
zone time specified.
SQL Commands
1 CREATE
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
1 SELECT
Creates a record.
3 UPDATE
Modifies records.
4 DELETE
Deletes records.
1 GRANT
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
Creating a table
The SQL syntax for creating a table is shown below:
CREATE TABLE <TABLE NAME>
(
COLUMN 1 NAME COLUMN 1 TYPE,
COLUMN 2 NAME COLUMN 2 TYPE,
.
.
COLUMN N NAME COLUMN N TYPE
);
Using the above syntax, to create the customers table, the SQL query will be as shown bellow:
CREATE TABLE Customers
(
FirstName VARCHAR(50),
LastName VARCHAR (50),
SSN NUMERIC(10),
Age NUMERIC(10),
City VARCHAR (32),
State VARCHAR (2),
Country VARCHAR (32)
);
While creating table, it’s very important to mention the type of data that will be stored in various
columns. VARCHAR is a standard data type for storing text data. NUMERIC is used for storing
numbers. The numbers in parenthesis represent the maximum length of data that can be stored.
Likewise, there are several other data type
Inserting the data into the table
To insert the data into the tables, we use the INSERT query. A single insert query inserts one
record or row of data. Following is the sql syntax.
INSERT INTO <TABLE NAME> VALUES (COL1 DATA, COL2 DATA …. COL (N)
DATA);
Using the above syntax, we insert the record into customers table as
INSERT INTO Customers VALUES (‘Smith’, ‘John’, 123456, 20,
‘Vegas’, ‘CA’, ‘USA’);
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
You can specify or ignore the column names while using INSERT INTO statement.
To insert partial column values, you must have to specify the column names. But if you
want to insert all the column values, you can specify or ignore the column names.
Here, column1, column2, column3,...columnN are the names of the columns in the table
into which you want to insert the data.
You may not need to specify the column(s) name in the SQL query if you are adding
values for all the columns of the table. But make sure the order of the values is in the
same order as the columns in the table
While using the INSERT sql,
Every data must be separated by a comma,
All the text data must be enclosed in single quotes,
Numeric data must not be enclosed in single quotes.
Updating records in table
To update the data in an existing record, we use the UPDATE query statement. The syntax for
this query is shown below:
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
Example:
UPDATE CUSTOMERS
SET FirstName = ‘Joe’, LastName = ‘Roberts’
WHERE
SSN = 123456
The above query will update all the customers firstname and lastname whose SSN equals to
123456.
Retrieving records from table
Retrieving the records is the most important database operation. We use the SELECT query to
retrieve the records. The syntax for this query is as shown below:
SELECT COL 1 NAME, COL2 NAME …… FROM <TABLE NAME> WHERE
<CONDITION>
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
If the query has no WHERE clause, then it retrieves the selected columns from all the records in
the table. Based on this, let’s see few cases here:
Case 1: Retrieve all the customers data
SELECT * from Customers;
In the above sql asterisk(*) means all columns of data. Since there is no WHERE clause in the
query, it will pull up all the records. The result of the above query is the entire table.
Case 2: Select all the customers who belong to the state of CA.
SELECT * FROM Customers WHERE State = ‘CA’;
The above query will retrieve those records whose state is CA
Case 3: Retrieve the first names and last names whose country is USA and state is CA (multiple
conditions)
SELECT firstName, lastName from Customers WHERE State=’CA’ AND
Country=’USA’;
Case 4: Let’s say we have the following two tables.
If you noticed the above two (Books and Authors) tables, they are joined together using the
ISBN column. If we need to pull the publisher, author, title and country (data in both the tables)
for a particular ISBN, we do so as shown below:
SELECT t1.Publisher, t1.Title, t2.Author, t2.Country from Books
t1, Authors t2 WHERE
t1.ISBN = t2.ISBN;
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
Whenever we need to pull data from multiple tables, we need to use alias names for tables. In the
above query, t1 is the alias name for Books table, and t2 is the alias name for Authors table.
Therefore, all the columns in books table must be prefixed with “t1.” and columns in authors
table must be prefixed with “t2.” as shown below:
SELECT t1.Publisher, t1.Title, t2.Author, t2.Country
Now, look at the where clause. Since we need to pull the data if the ISBN in both the tables
match, the where clause will be as shown below:
WHERE t1.ISBN = t2.ISBN;
Deleting the records
To delete the records in the table we use DELETE query. The syntax for this query is shown
below:
DELETE FROM <TABLE NAME> WHERE <CONDITION>
For instance, to delete all the customers whose state is CA, the query will be,
DELETE FROM Customers where State=’CA’;
The above SQL deletes 3 records in the customers table. These are all the basic SQL operations
you need to know to work with any database.
I am sure things are pretty simple. With this basic knowledge of databases and SQL, we are now
ready to learn JDBC technology to access databases.
What is JDBC?
JDBC stands for Java Database Connectivity which is a technology that allows Java applications
to interact with relational databases and execute SQL queries against the databases
JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc drivers
to connect with the database.
The JDBC API is a Java API that can access any kind of tabular data, especially data stored in a
Relational Database.
JDBC helps to write Java applications that manage these three programming activities:
Connect to a data source, like a database
Send queries and update statements to the database
Retrieve and process the results received from the database in answer to your query
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for
portable access to an underlying database. Java can be used to write different types of
executable, such as −
Java Applications
Java Applets
Java Servlets
Java ServerPages (JSPs)
Enterprise JavaBeans (EJBs).
All of these different executable are able to use a JDBC driver to access a database, and take
advantage of the stored data.
The above figure should tell you the complete story. Java applications simply use JDBC API to
interact with any database.
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
Database Drivers
A driver is not a hardware device. It’s 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.
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
friends helping each other. This is really cool as it completely eliminates the translation
process.
JDBC is Java based technology, and with the driver also written in Java, it can directly
invoke the driver program as if it were any other Java program.
This is the driver that all the J2EE applications use to interact with databases.
Because this is a Java to Java interaction, this driver offers the best performance.
MySQL's Connector/J driver is a Type 4 driver.
Which Driver should be Used?
If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred
driver type is 4.
If your Java application is accessing multiple types of databases at the same time, type 3
is the preferred driver.
Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet
for your database.
The type 1 driver is not considered a deployment-level driver, and is typically used for
development and testing purposes only.
JDBC API
JDBC technology is nothing but an API. It is a set of classes and interfaces that our Java
programs use to execute the SQL queries against the database. The fundamental idea behind
JDBC is that, Java programs use JDBC API, and JDBC API will in turn use the driver to work
with the database.
Therefore, to work with MySQL database, we need to configure the JDBC with all the MySQL
information. This information is nothing but:
Name of the MySQL driver class
URL of the database schema.
In simple words, for a Java program to work with the database, we first need to configure JDBC
with the above database info and then make the Java program use the JDBC.
Few class and interfaces of JDBC API are as follows:
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
The JDBC™ 4.3 ( Released in September 21, 2017) API includes both the java.sql package,
referred to as the JDBC core API, and the javax.sql package, referred to as the JDBC Optional
Package API. This complete JDBC API is included in the Java™ Standard Edition (Java SE™),
version 7. The javax.sql package extends the functionality of the JDBC API from a client-side
API to a server-side API, and it is an essential part of the Java™ Enterprise Edition (Java
EE™) technology.
JDBC programming is the simplest of all. There is a standard process we follow to execute the
SQL queries. Following lists the basic steps involved in any JDBC program.
Import necessary packages
Load and Register the Driver
Establish the connection to the database
Create the statements( using Statement/ PreparedStatement/ CallableStatement)
Execute the statements
Process the results
Close the statements
Close the connection.
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
The forName() method of Class class is used to register the driver class. This method is
used to dynamically load the driver class.
Example: Class.forName("oracle.jdbc.driver.OracleDriver");
The getConnection() method of DriverManager class is used to establish connection with
the database.
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system",
"password");
The createStatement() method of Connection interface is used to create statement. The
object of statement is responsible to execute queries with the database.
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
By closing connection object statement and ResultSet will be closed automatically. The
close() method of Connection interface is used to close the connection.
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
Database URLs
Database URL Formulation
After you've loaded the driver, you can establish a connection using
the DriverManager.getConnection() method. For easy reference, let me list the three
overloaded DriverManager.getConnection() methods −
getConnection(String url)
getConnection(String url, Properties prop)
getConnection(String url, String user, String password)
Here each form requires a database URL. A database URL is an address that points to your
database.
Formulating a database URL is where most of the problems associated with establishing a
connection occurs.
Following table lists down the popular JDBC driver names and database URL.
All the highlighted part in URL format is static and you need to change only the remaining part
as per your database setup.
When connecting to a database, you must use parameters like
host names,
port numbers, and
database names.
Syntax: jdbc:subprotocol:other_parameters
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
(Window ServicesDatabase)
o Confirm that the server host name and port are correct.
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
Notice that the IDE enters localhost as the default server host name and 3306 as
the default server port number.
Click the “Run Administration Tool” tab at the top of the dialog box.
The Admin Properties tab is then displayed, allowing you to enter information for
controlling the MySQL Server.
http://localhost/phpmyadmin/
o Create database and tables
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
Password: Password is given by the user at the time of installing the mysql database.
Next, we need an object reference to the Statement interface to submit SQL statements to the
database.
Processing the query result
The result of the query fired through the Statement object is contained by an object of
the ResultSet interface.
ResultSet rs =
statement.executeQuery("SELECT * FROM
Books")
Process ResultSet object using
while (rs.next())
{
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
Note: You can use execute method to execute arbitrary SQL statements Database column indices
start from 1
The Statement interface provides methods to execute queries with the database. The statement
interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.
Commonly used methods of Statement interface:
public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the
object of ResultSet.
public int executeUpdate(String sql): is used to execute specified query, it may be create,
drop, insert, update, delete etc.
public boolean execute(String sql): is used to execute queries that may return multiple
results.
public int[] executeBatch(): is used to execute batch of commands.
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
import java.sql.*;
class Example{
String db_username="root";
String db_password="";
//Create statements
Statement stmt=con.createStatement();
//Execute query
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
//closing statement
stmt.close();
//closing connection
con.close();
A resultset object can be imagined like a table of records with a pointer at the beginning
of the table as shown below:
To read the records, we need to move the pointer to the record using the next() method
until the pointer reaches the end of the records. This is what the while loop does. Once
we are in the loop, we need to read the record that the pointer points using the get
methods.
The get methods can either take the column number starting from 1 or the column name
itself.
In our example, the column numbers have been used.
Following are the most commonly used get methods:
public String getString() Used for VARCHAR columns
public int getInt() Used for NUMERIC columns
public Date getDate() Used for DATE columns.
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
Instead of specifying the column numbers, we can also specify the column names as
shown below:
String firstName = rs.getString(“fname”);
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
package jdbc_practice;
import java.sql.*;
public class ReadFromTable {
public static void main(String[] args) {
String className = "com.mysql.jdbc.Driver";
String db_url = "jdbc:mysql://localhost:3306/java2lab";
String db_username = "root";
String db_password = "";
try{
Class.forName(className);
Connection con;
Con=
DriverManager.getConnection(db_url,db_username,db_password);
Statement stmt;
stmt = con.createStatement();
String myquery = "SELECT * FROM students";
ResultSet rs;
rs = stmt.executeQuery(myquery);
int rn;
long phn;
String fn,ln,adr;
while(rs.next())
{
rn =rs.getInt(1);
fn =rs.getString(2);
ln = rs.getString(3);
phn = rs.getLong(4);
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
adr = rs.getString(5);
System.out.println("Roll Number:"+rn+"\t"
+"First Name:"+fn+"\t"
+"Last Name:"+ln+"\t"
+"Phone Number:"+phn+"\t"
+"Address:"+adr+"\t"
);
}
stmt.close();
con.close();
} catch(Exception excp){
System.out.println(excp);
}
}
}
Trick: If the query is SELECT, use the executeQuery() method. For all other
queries (CREATE, INSERT, DELETE, UPDATE etc) use the executeUpdate() method.
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
Task1:
Write a java program that allows a user to insert values to a table of
particular database (Suppose database is in MySql server ). The program
should take the values to insert from console.
Task2:
WAP using JDBC to display the records from a table of given database (Suppose
database is in MySql server ). Assume the following table :
result(roll_no , course_name ,marks_obtained)
The program should read the roll number value from console and display the
corresponding record.
//Task1 Code
package jdbc_practice;
import java.sql.*;
import java.util.Scanner;
public class Task1 {
private final String DRIVER_NAME = "com.mysql.jdbc.Driver";
private final String DB_URL
="jdbc:mysql://localhost:3306/java2lab";
private final String DB_USERNAME = "root";
private final String DB_PASSWORD = "";
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
int rn;
String course;
float marks;
private void connectMeAndFireQuery(){
try{
Class.forName(DRIVER_NAME);
Connection con;
con = DriverManager.getConnection(DB_URL, DB_USERNAME,
DB_PASSWORD);
String queryToFire = "INSERT INTO
result(roll_no,course_name,marks_obtained)" + "VALUES(" +this.rn
+","+"\'"+this.course+"\'"+","+this.marks+")";
Statement st;
st = con.createStatement();
int n;
n=st.executeUpdate(queryToFire);
System.out.println("Thank you "+ n+ " record is added!");
st.close();
con.close();
} catch (Exception e){
System.out.println(e);
}
}
private void getDataFromConsole(){
Scanner sc = new Scanner(System.in);
System.out.println("--Enter following informations--");
System.out.println("---Enter course name--- ");
course = sc.nextLine();
System.out.println("---Enter roll number--- ");
rn = sc.nextInt();
32 Collected by Bipin Timalsina
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
//Task2 Code
package jdbc_practice;
import java.sql.*;
import java.util.Scanner;
public class Task2 {
private final String DRIVER_NAME = "com.mysql.jdbc.Driver";
private final String DB_URL
="jdbc:mysql://localhost:3306/java2lab";
private final String DB_USERNAME = "root";
private final String DB_PASSWORD = "";
int rn;
String course;
float marks;
private void connectMeAndFireQuery(){
try{
Class.forName(DRIVER_NAME);
Connection con;
con = DriverManager.getConnection(DB_URL, DB_USERNAME,
DB_PASSWORD);
String queryToFire = "SELECT course_name,marks_obtained"
+ " FROM result"
+" WHERE roll_no ="+this.rn;
Statement st;
st = con.createStatement();
ResultSet record;
record=st.executeQuery(queryToFire);
while(record.next()){
course = record.getString("course_name");
marks = record.getFloat("marks_obtained");
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
System.out.println(
"Roll No: "+rn+"\t "
+"Course Name: "+ course+ "\t"
+"Marks: "+marks
);
}
st.close();
con.close();
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
PreparedStatement
Once a connection is obtained we can interact with the database. The JDBC Statement,
CallableStatement, and PreparedStatement interfaces define the methods and properties that
enable you to send SQL or PL/SQL commands and receive data from your database.
PreparedStatement Use this when you plan to use the SQL statements many
times. The PreparedStatement interface accepts input
parameters at runtime.
CallableStatement Use this when you want to access the database stored
procedures. The CallableStatement interface can also
accept runtime input parameters.
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
The SQL query to be passed to the above method will look as shown below:
String myQuery = “INSERT INTO students VALUES ( ?, ?, ?, ?, ?)”;
Since we need to insert data into five columns, we used five question marks. If you
notice the query, there are no single quotes like we had in earlier examples. Once we
have the above SQL query , we create the prepared statement as shown below:
PreparedStatement stmt = con.prepareStatement ( myQuery );
Step 2: Now that we created a prepared statement, its time to populate it with the data.
To do this, we use the setXXX() which methods bind values to the parameters,
where XXX represents the Java data type of the value you wish to bind to the input
parameterr. If you forget to supply the values, you will receive an SQLException.
Example:
stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan");
Always remember one thing. The numbers in the set methods denote the position of the
question mark symbol but not the column number in the table
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
Method Description
public void setInt(int paramIndex, int value) sets the integer value
to the given
parameter index.
public void setString(int paramIndex, String value) sets the String value
to the given
parameter index.
public void setFloat(int paramIndex, float value) sets the float value to
the given parameter
index.
public void setDouble(int paramIndex, double value) sets the double value
to the given
parameter index.
public int executeUpdate() executes the query. It
is used for create,
drop, insert, update,
delete etc.
public ResultSet executeQuery() executes the select
query. It returns an
instance of ResultSet.
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
package jdbc_practice;
import java.sql.*;
public class PSExample1 {
final String DRIVER_NAME = "com.mysql.jdbc.Driver";
final String DB_URL ="jdbc:mysql://localhost:3306/java2lab";
final String DB_USERNAME = "root";
final String DB_PASSWORD = "";
void connectMeAndFireQuery(){
try{
Class.forName(DRIVER_NAME);
Connection con;
con = DriverManager.getConnection(DB_URL, DB_USERNAME,
DB_PASSWORD);
String myQuery = "INSERT INTO students VALUES(?,?,?,?,?)";
PreparedStatement pstmt;
pstmt = con.prepareStatement(myQuery);
pstmt.setInt(1, 101);
pstmt.setString(2,"Ratan");
pstmt.setString(3,"Yadav");
pstmt.setLong(4,984100000);
pstmt.setString(5, "Saptari");
int n;
n=pstmt.executeUpdate();
System.out.println("Thank you "+ n+ " record is
added!");
pstmt.close();
con.close();
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
rs=pstmt.executeQuery();
while(rs.next()){
int rn = rs.getInt(1);
String course = rs.getString(2);
float marks= rs.getFloat(3);
System.out.println(
"Roll No: "+rn+"\t "
+"Course Name: "+ course+ "\t"
+"Marks: "+marks
);
}
pstmt.close();
con.close();
} catch (Exception e){
System.out.println(e);
}
}
public static void main(String[] args) {
PSExample2 pse2 =new PSExample2();
pse2.connectMeAndFireQuery();
}
}
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
package jdbc_practice;
import java.sql.*;
import java.util.Scanner;
public class PSExample3 {
final String DRIVER_NAME = "com.mysql.jdbc.Driver";
final String DB_URL
="jdbc:mysql://localhost:3306/java2lab";
final String DB_USERNAME = "root";
final String DB_PASSWORD = "";
int rn;
void getRoll(){
Scanner sc = new Scanner(System.in);
System.out.println("Whose data is to be deleted? Enter
Roll No: ");
rn = sc.nextInt();
}
void connectMeAndFireQuery(){
try{
Class.forName(DRIVER_NAME);
Connection con;
con = DriverManager.getConnection(DB_URL, DB_USERNAME,
DB_PASSWORD);
String myQuery = "DELETE FROM students WHERE roll_no =?
";
PreparedStatement pstmt;
pstmt = con.prepareStatement(myQuery);
pstmt.setInt(1, rn);
int n = pstmt.executeUpdate();
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
Task3:
Write a java program using PreparedStatement that allows a user to
insert values to a table of particular database (Suppose database is in
MySql server ). The program should take the values to insert from
console as long as user want to add new record.
Task4:
WAP using PreparedStatement to display the records from a table of given database
(Suppose database is in MySql server ). Assume the following table :
salary(emp_id , emp_name ,emp_salary)
The program should read the employee id value from console and display the
corresponding record.
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
//Task3 code
package jdbc_practice;
import java.sql.*;
import java.util.Scanner;
public class Task3 {
final String DRIVER_NAME = "com.mysql.jdbc.Driver";
final String DB_URL
="jdbc:mysql://localhost:3306/java2lab";
final String DB_USERNAME = "root";
final String DB_PASSWORD = "";
static int count;
int rn;
String course;
Float marks;
void getData(){
Scanner sc1 = new Scanner(System.in);
System.out.println("Enter Course Name:");
course =sc1.nextLine();
System.out.println("Enter Roll Number:");
rn = sc1.nextInt();
System.out.println("Enter Marks:");
marks = sc1.nextFloat();
}
void connectMeAndFireQuery(){
try{
Class.forName(DRIVER_NAME);
Connection con;
con = DriverManager.getConnection(DB_URL, DB_USERNAME,
DB_PASSWORD);
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
//Task4 code
package jdbc_practice;
import java.sql.*;
import java.util.Scanner;
public class Task4 {
final String DRIVER_NAME = "com.mysql.jdbc.Driver";
final String DB_URL
="jdbc:mysql://localhost:3306/java2lab";
final String DB_USERNAME = "root";
final String DB_PASSWORD = "";
int eid;
void getEmpID(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter Employee ID: ");
eid = sc.nextInt();
}
void connectMeAndFireQuery(){
try{
Class.forName(DRIVER_NAME);
Connection con;
con = DriverManager.getConnection(DB_URL, DB_USERNAME,
DB_PASSWORD);
String myQuery = "SELECT emp_name,emp_salary FROM salary
WHERE emp_id =?";
PreparedStatement pstmt;
pstmt = con.prepareStatement(myQuery);
pstmt.setInt(1,this.eid);
ResultSet rs;
rs = pstmt.executeQuery();
while(rs.next())
49 Collected by Bipin Timalsina
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
{
String name= rs.getString("emp_name");
double sal = rs.getDouble("emp_salary");
System.out.println("Employee ID = " +eid +"\t"
+ "Employee Name = "+ name+"\t"
+"Salary = "+sal
);
}
pstmt.close();
con.close();
} catch (Exception e){
System.out.println(e);
}
}
public static void main(String[] args) {
Task4 t4 =new Task4();
t4.getEmpID();
t4.connectMeAndFireQuery();
}
}
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
Connection Pooling
Establishing a database connection is a very resource-intensive process and involves a lot
of overhead.
Connection pooling is a mechanism to create and maintain a collection of JDBC
connection objects. The primary objective of maintaining the pool of connection object is
to leverage re-usability. A new connection object is created only when there are no
connection objects available to reuse. This technique can improve overall performance of
the application
Connection pooling mechanism manage the connections effectively and efficiently by
optimizing the usage of database connections
The connection pooling program comes along when we download the drivers for a
particular database
The way the connection pooling works is,
1. It initializes a pool of connections with the database.
2. When a connection is requested by the application, it returns a connection from
the pool.
3. The application after using the connection returns it back to the pool.
Connection pooling will be implemented in such a way that all the details are hidden
behind the scenes. The only change we as application developers need to make is the way
we retrieve the connection object. Once we get a connection object, the rest of the
program will be the same.
Connection pooling is usually used with large scale enterprise applications where
thousands of processes need to access the database at the same time. In such situations
the application server will be configured to use the connection pooling.
https://genuinenotes.com
https://genuinenotes.com
Unit-8/ Java Programming - II
https://genuinenotes.com