0% found this document useful (0 votes)
33 views58 pages

JDBC Introduction

Uploaded by

srsartandcraft21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views58 pages

JDBC Introduction

Uploaded by

srsartandcraft21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

JDBC Introduction

JDBC :
❖ JDBC API is a Java API that can access any kind of tabular data,
especially data stored in a Relational Database.
❖ JDBC works with Java on a variety of platforms, such as Windows, Mac
OS, and the various versions of UNIX.
❖ JDBC stands for Java Database Connectivity, which is a standard Java
API for database-independent connectivity between the Java
programming language and a wide range of databases.
❖ The JDBC library includes APIs for each of the tasks mentioned below
that are commonly associated with database usage.
● Making a connection to a database.
● Creating SQL or MySQL statements.
● Executing SQL or MySQL queries in the database.
● Viewing & Modifying the resulting records.
Applications of JDBC :
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 executables, such as −

● Java Applications
● Java Applets
● Java Servlets
● Java ServerPages (JSPs)
● Enterprise JavaBeans (EJBs).

All of these different executables are able to use a JDBC driver to access a database,
and take advantage of the stored data.

JDBC provides the same capabilities as ODBC, allowing Java programs to contain
database-independent code. Interacting with a database requires efficient database
connectivity, which can be achieved by using the ODBC(Open database connectivity) driver.
This driver is used with JDBC to interact or communicate with various kinds of databases
such as Oracle, MS Access, Mysql, and SQL server database.
Components of JDBC :

1. JDBC API: It provides various methods and interfaces for easy


communication with the database.

2. JDBC Driver manager: It loads a database-specific driver in an application


to establish a connection with a database. It is used to make a database-specific
call to the database to process the user request.
3. JDBC Test suite: It is used to test the operation(such as insertion, deletion,
updation) being performed by JDBC Drivers.
4. JDBC-ODBC Bridge Drivers: It connects database drivers to the database.
This bridge translates the JDBC method call to the ODBC function call. It makes
use of the sun.jdbc.odbc package which includes a native library to access
ODBC characteristics.
1.Application: It is a java applet or a servlet
Architecture of JDBC :
that communicates with a data source.
2.The JDBC API: The JDBC API allows Java
programs to execute SQL statements and
retrieve results.
3.DriverManager: It uses some
database-specific drivers to effectively connect
enterprise applications to databases.
4.JDBC drivers: To communicate with a data
source through JDBC, you need a JDBC driver
that intelligently communicates with the
respective data source.
The JDBC classes are contained in the Java
JDBC :
Package java.sql and javax.sql.
JDBC helps you to write Java applications that
manage these three programming activities:
1. Connect to a data source, like a
database.
2. Send queries and update statements to
the database
3. Retrieve and process the results received
from the database in answer to your
query
JDBC Drivers :

JDBC drivers are client-side adapters (installed on the client machine, not on the
server) that convert requests from Java programs to a protocol that the DBMS can
understand. There are 4 types of JDBC drivers:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Thin driver
Type-1 Driver : Type-1 driver or JDBC-ODBC bridge driver
uses ODBC driver to connect to the database.
The JDBC-ODBC bridge driver converts JDBC
method calls into the ODBC function calls.
Type-1 driver is also called Universal driver
because it can be used to connect to any of
the databases.
●As a common driver is used in order to
interact with different databases, the data
transferred through this driver is not so
secured.
●The ODBC bridge driver is needed to be
installed in individual client machines.
●Type-1 driver isn’t written in java, that’s
why it isn’t a portable driver.
Vendor based database libraries means you need to use ●It is a database independent driver.
libraries provided by vendors to connect to database. For
example You need to use ojdbc6.jar for Oracle ,
postgresql-9.4.1207.jar for postgresql etc
Type-2 Driver : The Native API driver uses the client
-side libraries of the database. This
driver converts JDBC method calls
into native calls of the database API.
In order to interact with different
database, this driver needs their local
API, that’s why data transfer is much
more secure as compared to type-1
driver.
● Driver needs to be installed
separately in individual client
machines
● The Vendor client library needs to
be installed on client machine.
● Type-2 driver isn’t written in java,
that’s why it isn’t a portable driver
● It is a database dependent driver.
Type-3 Driver : The Network Protocol driver uses middleware
(application server) that converts JDBC calls
directly or indirectly into the vendor-specific
database protocol. Here all the database
connectivity drivers are present in a single
server, hence no need of individual client-side
installation.
● Type-3 drivers are fully written in
Java, hence they are portable drivers.
● No client side library is required
because of application server that can
perform many tasks like auditing, load
balancing, logging etc.
● Network support is required on client
machine.
● Maintenance of Network Protocol
driver becomes costly because it
requires database-specific coding to
be done in the middle tier.
● Switch facility to switch over from one
database to another database.
Type-4 Driver : Type-4 driver is also called native protocol driver. This driver
interact directly with database. It does not require any native
database library, that is why it is also known as Thin Driver.
● Does not require any native library and Middleware
server, so no client-side or server-side installation.
● It is fully written in Java language, hence they are
portable drivers.

Which Driver to use When?

● If you are accessing one type of database, such as Oracle, Sybase,


or IBM, the preferred driver type is type-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.
• In a two-tier model, a Java application
JDBC two tier model :
communicates directly with the database,
via the JDBC driver.
• In the two-tier model, a Java applet or
application talks directly to the data source.
• This requires a JDBC driver that can
communicate with the particular data
source being accessed.
• A user's commands are delivered to the
database or other data source, and the
results of those statements are sent back to
the user.
• The data source may be located on another
machine to which the user is connected via
a network.
JDBC three tier model :
• In a three-tier model, a Java application
communicates with a middle tier
component that functions as an
application server. The application server
talks to a given database using JDBC.
• In the three-tier model, commands are
sent to a "middle tier" of services, which
then sends the commands to the data
source.
• The data source processes the commands
and sends the results back to the middle
tier, which then sends them to the user.
Application Server?
An application server is a program that resides on the server-side, and it’s a server programmer providing business logic behind any
application. This server can be a part of the network or the distributed network.

Working
They are basically used in a web-based application that has 3 tier architecture. The position at which the application server fits in is
described below:

● Tier 1 – This is a GUI interface that resides at the client end and is usually a thin client (e.g. browser)
● Tier 2 – This is called the middle tier, which consists of the Application Server.
● Tier 3 – This is the 3rd tier which is backend servers. E.g., a Database Server.
As we can see, they usually communicate with the webserver for serving any request that is coming from
clients. The client first makes a request, which goes to the webserver. The web server then sends it to the
middle tier, i.e. the application server, which further gets the information from 3 rd tier (e.g. database server)
and sends it back to the webserver. The web server further sends back the required information to the client.
Different approaches are being utilized to process requests through the web servers, and some of them are
approaches like JSP (Java server pages), CGI(Common Gateway Interface), ASP (Active Server Pages), Java
Scripts, Java servlets, etc.
Common JDBC Components

• The JDBC API provides the following interfaces and classes −


• DriverManager Class
• Connection Interface
• Statement Interface
• PreparedStatement Interface
• ResultSet Interface
DriverManager Class A driver is a software component that allows Java applications to interact
with databases
It provides method for loading specific database drivers & for establishing connection to database.
• The DriverManager class acts as an interface between user and drivers.
• It keeps track of the drivers that are available and handles establishing a connection between a
database and the appropriate driver.
• The Class.forName() method is used to register the driver class. This method is used to dynamically
load the driver class. The Class.forName is used to load any given class (within double quotes as
String) at run time.
• Syntax of forName() method
public static void forName(String className) throws ClassNotFoundException
• Example to register with JDBC-ODBC Driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // Driver class for Access Database
• Class.forName("oracle.jdbc.driver.OracleDriver"); //Driver class for Oracle Database
• Class.forName("com.mysql.cj.jdbc.Driver") //Driver class for MySQL Database
• Following method is used to establish connection with specific database
• Connection cn = DriverManager.getConnection(URL, username, password);
• Ex. Connection cn = DriverManager.getConnection(“jdbc:odbc:datasource”, username, password);
//Establishing connection with MS Access
Commonly used methods of DriverManager class
Method Description

is used to register the given driver


public static void registerDriver( Driver driver);
with DriverManager.

is used to deregister the given driver


public static void deregisterDriver( Driver driver); (drop the driver from the list) with
DriverManager.

public static Connection getConnection ( String is used to establish the connection


url); with the specified url.

is used to establish the connection


public static Connection getConnection( String url,
with the specified url, username and
String userName, String password);
password.
Connection Interface
• Connection interface is used to establish connection between application and
database.
• A Connection is the session between java application and database.

• The Connection interface provides many methods for transaction management


like commit(), rollback() etc.

• When getConnection() method is called, it returns a connection object.

Connection
cn=DriverManager.getConnection(URL);
Commonly used methods of Connection interface
Method Description
public Statement createStatement(); creates a statement object that can be
Ex. Statement st=cn.createStatement(); used to execute SQL queries.

public void setAutoCommit(boolean It is used to set the commit status. By


status); default it is true.

It saves the changes made since the


public void commit(); previous commit/rollback permanent.
Drops all changes made since the
public void rollback(); previous commit/rollback.
public void close(); closes the connection and Releases a
JDBC resources immediately.
Ex. cn.close();
Statement Interface
• The Statement interface provides methods to execute queries with the
database.

• It provides factory method to get the object of ResultSet.


• PreparedStatement interface
• The PreparedStatement interface is a subinterface of Statement. It is used to execute parameterized query.
• String sql="insert into emp values(?,?,?)";
Commonly used methods of Statement interface
Method Description
public ResultSet executeQuery(String sql);
used to execute SELECT query. It returns the
Ex. ResultSet rs=st.executeQuery(“Select * object of ResultSet.
from student”);
public int executeUpdate(String sql);
used to execute specified query, it may be create,
Ex. st.executeUpdate(Create table student drop, insert, update, delete etc.
(rollno integer(10), name varchar(20))”);
Returns a boolean value of true if a ResultSet object
public boolean execute(String sql); can be retrieved; otherwise, it returns false. Use this
method to execute SQL DDL statements
void close() Close the statement object
ResultSet Interface
• It represents database resultset.

• A ResultSet object provides access to a table of data.

• ResultSet object is usually generated by executing a statement.

• The object of ResultSet maintains a cursor pointing to a particular row of data.

• Initially, cursor points before the first row.


Commonly used methods of ResultSet interface
Method Description
public boolean next(); is used to move the cursor to the one row next from the current position.
public boolean previous(); is used to move the cursor to the one row previous from the current position.This
method returns false if the previous row is off the result set.
public boolean first(); is used to move the cursor to the first row in result set object.
public boolean last(); is used to move the cursor to the last row in result set object.
public boolean absolute(int row); is used to move the cursor to the specified row number in the ResultSet object.
public int getInt(int columnIndex); is used to return the data of specified column index of the current row as int.
public int getInt(String columnName); is used to return the data of specified column name of the current row as int.
public String getString(int is used to return the data of specified column index of the current row as String.
columnIndex);
public String getString(String is used to return the data of specified column name of the current row as String.
columnName);
public int getFloat(int columnIndex);
public int getFloat(String
columnName);
public int getDouble(int columnIndex);

public int getDouble(String


Connecting to Database

• There are 5 steps to connect any java application with the database in java
using JDBC. They are as follows:

1. Register the driver class


2. Creating connection
3. Creating statement
4. Executing queries
5. Closing connection
1.Register the driver class
• The Class.forName() method is used to register the driver class. This method is used to dynamically load
the driver class. The Class.forName is used to load any given class (within
double quotes as String) at run time.

• Syntax of forName() method


public static void forName(String className)throws ClassNotFoundException

• Example to register with JDBC-ODBC Driver


Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
1.Register the driver class
• Approach I - Class.forName()
• The Class.forName() method is used to register the driver class. This method is used to
dynamically load the driver class. The Class.forName is used to load any given class
(within double quotes as String) at run time.
• Syntax of forName() method
public static void forName(String className)throws ClassNotFoundException
• Example to register with JDBC-ODBC Driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Class.forName("oracle.jdbc.driver.OracleDriver");

Approach II - DriverManager.registerDriver()
The second approach you can use to register a driver, is to use the static
DriverManager.registerDriver() method. Ex.
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
2. Creating connection
• The DriverManager.getConnection() method is used to establish connection with the
database.

• Example establish connection with Oracle


Driver
Connection con = DriverManager.getConnection
("jdbc:odbc:DemoDB","username","password");
3. Creating statement
• The createStatement() method of Connection
interface is used to create statement. The object of
statement is responsible to execute queries with the
database. lCreates a Statement object for sending SQL
statements to the database

• Example to create the statement object


Statement stmt=con.createStatement();
4. Executing queries
• The executeQuery() method of Statement interface is used to execute queries to
the database.
• This method returns the object of ResultSet that can be used to get all the records
of a table.

• Example to execute query

ResultSet rs=stmt.executeQuery("select * from emp");


while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
5. Closing connection
• By closing connection object statement and
ResultSet will be closed automatically.
• The close() method of Connection interface is
used to close the connection.

• Example to close connection

con.close();
//WAP to display data of student table
import java.sql.*;
class ConnectAccess1Demo{
public static void main(String args[]) throws Exception
{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn=DriverManager.getConnection("jdbc:odbc:Mydsn");
Statement st=cn.createStatement();
ResultSet rs=st.executeQuery(“Select * from student”);
while(rs.next())
{
System.out.println(“RollNo. : ” + getInt(1));
System.out.println(“Name : ” + getString(2));
}
cn.close();
}
//WAP to create table using jdbc
import java.sql.*;
class ConnectAccess1Demo{
public static void main(String args[]) throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn=DriverManager.getConnection("jdbc:odbc:Mydsn");
Statement st=cn.createStatement();
String str= “Create table emp(emp_name varchar(20), emp_id number)”
st.executeUpdate(str);
System.out.println(“Table created” );
cn.close();
}
}
//WAP to insert data into emp table
import java.sql.*;
class ConnectAccess1Demo{
public static void main(String args[]) throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn=DriverManager.getConnection("jdbc:odbc:Mydsn");
Statement st=cn.createStatement();
st.executeUpdate(“insert into emp values(“abc”,1)”);
st.executeUpdate(“insert into emp values(“pqr”,2)”);
System.out.println(“Records inserted” );
cn.close();
}
}
//WAP to crate table, insert and display data into emp table
import java.sql.*;
class ConnectAccess1Demo{
public static void main(String args[]) throws Exception
{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn=DriverManager.getConnection("jdbc:odbc:Mydsn");
Statement st=cn.createStatement();
String str= “Create table emp(emp_name varchar(20), emp_id number)”
st.executeUpdate(str);
System.out.println(“Table created” );
st.executeUpdate(“insert into emp values(“abc”,1)”);
st.executeUpdate(“insert into emp values(“pqr”,2)”);
System.out.println(“Records inserted” );
ResultSet rs= “select * from emp”;
st.executeQuery();
while(rs.next())
{System.out.println(“Emp_ID : ” + getInt(2));
System.out.println(“Emp_Name : ” + getString(1));
}
cn.close(); }
Steps to Connect Java Application with
mysql database example
1. Create 2 folders : lib and src on C drive
2. Download Sql connector [MySQL :: Download Connector/J]
And select Operating system - platform independent , Download its zip folder, Extract
that folder, and copy “mysql-connector-j-8.1.0” executable jar file to C:\db\lib folder
3. Download xamppserver and start - Apache and MySQL
4. To create database in MySQL click Admin button in front of
xamppserver
5. Create a new database student_db here
Then create table student_info having fields
enrollNo, name, dept, division
6. Write and save program RetrieveStudentInfo.java
in src folder
import java.sql.Connection;

8.
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class RetrieveStudentInfo {
public static void main(String[] args) {
// Database connection parameters
Class.forName("com.mysql.jdbc.Driver");
String jdbcURL = "jdbc:mysql://localhost:3306/student_db";
String username = "root";
String password = "";
// SQL query to retrieve values
String sqlQuery = "SELECT enrollNo, name, dept, division FROM student_info";
try (Connection connection = DriverManager.getConnection(jdbcURL, username, password);
PreparedStatement preparedStatement = connection.prepareStatement(sqlQuery);
ResultSet resultSet = preparedStatement.executeQuery()) {
// Loop through the result set and print values
while (resultSet.next()) {
int enrollNo = resultSet.getInt("enrollNo");
String name = resultSet.getString("name");
String dept = resultSet.getString("dept");
String division = resultSet.getString("division");
/*System.out.println("EnrollmentNo : " + enrollNo + ", StudentName : " + name +
",Department : " + dept + ",Division : " + division); */
System.out.println(enrollNo +" "+ name +" "+ dept +" "+ division);
} } catch (SQLException e) { e.printStackTrace(); } }}

/* javac -classpath ..\lib\mysql-connector-j-8.1.0.jar;. RetrieveStudentInfo.java


java -classpath ..\lib\mysql-connector-j-8.1.0.jar;. RetrieveStudentInfo */
7. Compile and execute program
/* javac -classpath ..\lib\mysql-connector-j-8.1.0.jar;.
RetrieveStudentInfo.java

java -classpath ..\lib\mysql-connector-j-8.1.0.jar;.


RetrieveStudentInfo */
Example to Connect Java Application
with mysql database
import java.sql.*;
class MysqlCon{
public static void main(String args[])
{
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/Emp","root","root");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}
catch(Exception e) {
System.out.println(e); }
}
PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query.
Let's see the example of parameterized query:
1. String sql="insert into emp values(?,?)"; or insert into stud values(?,?);
As you can see, we are passing parameter (?) for the values. Its value will be set by
calling the setter methods of PreparedStatement.
Why use PreparedStatement?
Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.
How to get the instance of PreparedStatement?
The prepareStatement() method of Connection interface is used to return the object of
PreparedStatement. Syntax:
1. public PreparedStatement prepareStatement(String query)throws
SQLException{}
The important methods of PreparedStatement interface are given below:
Method Description
public void setInt(int paramIndex, int value); sets the integer value to the given parameter index.
Ex. p.setInt(1,10);
public void setString(int paramIndex, String sets the String value to the given parameter index.
value)
Ex.: p.setString(2, “abc”);
public void setFloat(int paramIndex, float value) sets the float value to the given parameter index.

public void setDouble(int paramIndex, double sets the double value to the given parameter index.
value)

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.
Example of PreparedStatement interface that inserts the record
First of all create table as given below:
1. create table student(roll_no number(10), name varchar2(50));
Now insert records in this table by the code given below:
import java.sql.*;
class UpdateDemo{
public static void main(String args[])
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn=DriverManager.getConnection("jdbc:odbc:Mydsn");
PreparedStatement p=cn.prepareStatement( "insert into student values (?,?)" );
p.setInt(1,10);
p.setInt(1,20);
p.setString(2,"abc");
p.setString(2,"pqr");
p.executeUpdate();
System.out.println("values inserted");
}}
Example of PreparedStatement interface that inserts the record
First of all create table as given below:
1. create table emp(id number(10),name varchar2(50));
Now insert records in this table by the code given below:

1. import java.sql.*;
2. class InsertPrepared{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
7. PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
8. stmt.setInt(1,101);//1 specifies the first parameter in the query
9. stmt.setString(2,"Rtan");
10. int i=stmt.executeUpdate();
11. System.out.println(i+" records inserted");
12. con.close(); }catch(Exception e){ System.out.println(e);} } }
Example of PreparedStatement to insert records until user press n

1. import java.sql.*;
2. import java.io.*;
3. class RS{
4. public static void main(String args[])throws Exception{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
7. PreparedStatement ps=con.prepareStatement("insert into emp130 values(?,?,?)");
8. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
9. do{
10. System.out.println("enter id:");
11. int id=Integer.parseInt(br.readLine());
12. System.out.println("enter name:");
13. String name=br.readLine();
14. System.out.println("enter salary:");
15. float salary=Float.parseFloat(br.readLine());
1. ps.setInt(1,id);
2. ps.setString(2,name);
3. ps.setFloat(3,salary);
4. int i=ps.executeUpdate();
5. System.out.println(i+" records affected");
6.
7. System.out.println("Do you want to continue: y/n");
8. String s=br.readLine();
9. if(s.startsWith("n")){
10. break;
11. }
12. }while(true);
13.
14. con.close();
15. }}
Example of PreparedStatement interface that updates the record
1. PreparedStatement stmt=con.prepareStatement("update emp set name=? where id=?");
2. stmt.setString(1,"Ratna");//1 specifies the first parameter in the query i.e. name
3. stmt.setInt(2,101);
4.
5. int i=stmt.executeUpdate();
6. System.out.println(i+" records updated");

Example of PreparedStatement interface that deletes the record


1. PreparedStatement stmt=con.prepareStatement("delete from emp where id=?");
2. stmt.setInt(1,101);
3.
4. int i=stmt.executeUpdate();
5. System.out.println(i+" records deleted");
Example of PreparedStatement interface that retrieve the records of a
table
1. PreparedStatement stmt=con.prepareStatement("select * from
emp");
2. ResultSet rs=stmt.executeQuery();
3. while(rs.next()){
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));
5. }
Example of PreparedStatement to insert records until
1. System.out.println("enter salary:");
user press n
2. float salary=Float.parseFloat(br.readLine());
1. import java.sql.*;
3.
2. import java.io.*;
4. ps.setInt(1,id);
3. class RS{
5. ps.setString(2,name);
4. public static void main(String args[])throws
6. ps.setFloat(3,salary);
Exception{
7. int i=ps.executeUpdate();
5. Class.forName("oracle.jdbc.driver.OracleDriver");
8. System.out.println(i+" records affected");
6. Connection
9.
con=DriverManager.getConnection("jdbc:oracle:th
10. System.out.println("Do you want to continue:
in:@localhost:1521:xe","system","oracle");
y/n");
7. PreparedStatement
11. String s=br.readLine();
ps=con.prepareStatement("insert into emp130
12. if(s.startsWith("n")){
values(?,?,?)");
13. break;
8. BufferedReader br=new BufferedReader(new
14. }
InputStreamReader(System.in));
15. }while(true);
9. do{
16.
10. System.out.println("enter id:");
17. con.close();
11. int id=Integer.parseInt(br.readLine());
18. }}
12. System.out.println("enter name:");
13. String name=br.readLine();
Connection with Access Database
import java.sql.*;
public class JdbcAccessTest {
public static void main(String[] args) {
String databaseURL = "jdbc:ucanaccess://e://Contacts.accdb";
try (
Connection connection = DriverManager.getConnection(databaseURL)) {
String sql = "INSERT INTO Contacts (Full_Name, Email, Phone) VALUES (?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, "Rohit");
preparedStatement.setString(2, "[email protected]");
preparedStatement.setString(3, "0919989998");
int row = preparedStatement.executeUpdate();

if (row > 0) {
System.out.println("A row has been inserted successfully.");
}
sql = "SELECT * FROM Contacts";
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(sql);
while (result.next()) {
int id = result.getInt("Contact_ID");
String fullname = result.getString("Full_Name");
String email = result.getString("Email");
String phone = result.getString("Phone");
System.out.println(id + ", " + fullname + ", " + email + ", " + phone);
}
} catch (SQLException ex) {
ex.printStackTrace();
} }}

You might also like