0% found this document useful (0 votes)
9 views10 pages

Understanding Java JDBC Basics

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

Understanding Java JDBC Basics

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

What Is Java JDBC?

JDBC is an abbreviation for the term Java Database Connection. JDBC is a


software tool, also known as an application programming interface that establishes
a connection between a standard database and Java application that intends to use
that database.
Need for Java JDBC
JDBC is used for multiple applications to connect to various types of data storage
units that are both standard and advanced. We need JDBC for the following
purposes.
 For establishing stable database connectivity with the application API.
 To execute SQL(Structured Query Language) queries and DDL/DML
commands.
 For viewing and modify data records in the data storage units.
Java JDBC Architecture
The Java JDBC architecture consists of the following primary segments. They are:
 JDBC Application
 JDBC API
 JDBC Manager
 JDBC Drivers
 Data Storage Units

1
Steps to Connect Java JDBC
There are eight crucial steps to be followed to establish the JDBC connection and
process the data. Those steps are as follows:
 Import-Package Dependencies
 Load and Register the Driver
 Connect to the Database
 Frame Query
 Execute Query
 Process Result
 Close Statement
 Close connection

2
Establishing Connection in JDBC

[Link] ():
This method loads the driver class files into memory during the run time. You don't
have to use new objects or create objects. In the following example uses
[Link] () to load the Oracle driver as follows:
The syntax for this is Syntax:
 [Link](“[Link]”)
Establish a connection using the Connection class object
After loading the driver, establish connections as shown below as follows:
Connection con = [Link](url,user,password)

• user: Username from which your SQL command prompt can be accessed.
• password: password from which the SQL command prompt can be accessed.
• con: It is a reference to the Connection interface.
• Url: Uniform Resource Locator which is created as shown below:
String url = “ jdbc:oracle:thin:@localhost:1521:xe”
Example:
Connection
con=[Link]("jdbc:oracle:thin:@localhost:1521:xe","system
","root");
 jdbc:oracle:thin:@loca;
 lhost:1521:xe where jdbc is the API, oracle is the database, thin is the driver,
localhost is the server name on which oracle is running, we may also use IP
address, 1521 is the port number and XE is the Oracle service name.

3
Connection Establishment:
[Link]("[Link]");

con=[Link]("jdbc:oracle:thin:@localhost:1521:xe","system
","root");
[Link]("Connection established");
Inserting record In to table:
A PreparedStatement is a pre-compiled SQL statement. It is a subinterface of
Statement.
Advantages of PreparedStatement
 When PreparedStatement is created, the SQL query is passed as a parameter.
This Prepared Statement contains a pre-compiled SQL query, so when the
PreparedStatement is executed, DBMS can just run the query instead of first
compiling it.
 We can use the same PreparedStatement and supply with different
parameters at the time of execution.
Methods of PreparedStatement:
 setInt(int, int): This method can be used to set integer value at the given
parameter index.
 setString(int, string): This method can be used to set string value at the given
parameter index.
 setFloat(int, float): This method can be used to set float value at the given
parameter index.
 setDouble(int, double): This method can be used to set a double value at the
given parameter index.
 executeUpdate(): This method can be used to create, drop, insert, update,
delete etc. It returns int type.

4
 executeQuery(): It returns an instance of ResultSet when a select query is
executed.
PreparedStatement psmt=[Link]("insert into emps
values(?,?,?)");
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));
while(true) {
[Link]("enter emp no");
int eno=[Link]([Link]());
[Link]("enter emp name");
String name=[Link]();
[Link]("enter salary");
int sal=[Link]([Link]());
[Link](1, eno);
[Link](2, name);
[Link](3, sal);
int count=[Link]();
if(count>0)
[Link](count+" Records are inserted");
else
[Link]("No recoed inserted");
[Link]("Do you want continue(yes/no)?");
String ch=[Link]();
if([Link]("no"))
break;
}

5
For select statement
PreparedStatement pstmt = null;
ResultSet rst = null;
String myQuery = "select Id,Name,Age from JavaPreparedStatement";
try {
con = [Link](JdbcURL, Username, password);
pstmt = [Link](myQuery);
rst = [Link]();
[Link]("Id\t\tName\t\tAge
");
while([Link]()) {
[Link]([Link](1));
[Link]("\t\t"+[Link](2));
[Link]("\t\t"+[Link](3));
[Link]();
}
} catch(Exception exec) {
[Link]();
}
}
}

6
String query = "select * from tblemployee";
stmt = [Link]();
ResultSet rs = [Link](query);
while ([Link]())
{
Integer empId = [Link](1);
String firstName = [Link](2);
String lastName = [Link](3);
Date dob = [Link](4);
[Link]("empId:" + empId);
[Link]("firstName:" + firstName);
[Link]("lastName:" + lastName);
[Link]("dob:" + dob);
[Link]("");

7
Create table Statement
Statement smt=[Link]();
[Link]("create table emp(eno number(5).ename char(10),sal
number(10));
Insert statement
PreparedStatement psmt=[Link]("insert into emps values(?,?,?)");
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));
while(true) {
[Link]("enter emp no");
int eno=[Link]([Link]());
[Link]("enter emp name");
String name=[Link]();
[Link]("enter salary");
int sal=[Link]([Link]());
[Link](1, eno);
[Link](2, name);
[Link](3, sal);
int count=[Link]();

8
Select staement
String query = "select * from tblemployee";
Staement stmt = [Link]();
ResultSet rs = [Link](query);
while ([Link]())
{
Integer empId = [Link](1);
String firstName = [Link](2);
String lastName = [Link](3);
Date dob = [Link](4);
[Link]("empId:" + empId);
[Link]("firstName:" + firstName);
[Link]("lastName:" + lastName);
[Link]("dob:" + dob);
[Link]("");

9
JUnit Tutorial
[Link]

10

Common questions

Powered by AI

The setInt and setString methods within a PreparedStatement allow parameters to be set dynamically with integer and string values. This enables the reuse of SQL statements with different input values without recompiling, improving performance, reducing errors, and protecting against SQL injection. These methods also help to ensure type correctness and enhance code readability .

PreparedStatement enhances database interaction by allowing SQL queries to be pre-compiled, reducing execution time for repeated executions and providing protection against SQL injection attacks. It allows setting parameters for execution, which can be reused with different values without recompiling the SQL, thus improving performance and security .

In JDBC, Class.forName() is used to load the JDBC driver class dynamically at runtime, while DriverManager.getConnection() establishes a connection to a specified database. An example is: Class.forName('oracle.jdbc.driver.OracleDriver'); Connection con = DriverManager.getConnection('jdbc:oracle:thin:@localhost:1521:xe', 'system', 'root');. This connects to an Oracle database using the provided URL, username, and password .

Establishing a JDBC connection in a Java application involves the following steps: Import Package Dependencies, Load and Register the Driver, Connect to the Database, Frame Query, Execute Query, Process Result, Close Statement, and Close Connection .

The JDBC Manager acts as an intermediary between the application and the driver. It manages the connection between the Java application and the database driver, facilitating database access and resource management, ensuring proper use of driver implementations as per the application's requirements .

ResultSet is used with PreparedStatement in JDBC to handle and iterate over data retrieved from a query execution, such as for SELECT statements. It allows access to the data returned from a database query using methods like getInt() for integers, getString() for strings, etc., enabling developers to iterate through records and perform operations on the data .

The executeUpdate method is typically used for performing operations like INSERT, UPDATE, DELETE, and DDL statements such as creating or dropping tables, where it returns an integer indicating the number of rows affected. The executeQuery method is used for executing SELECT queries, returning a ResultSet object to handle the query results .

Pre-compilation in PreparedStatements is beneficial as it allows SQL queries to be compiled once and reused multiple times, which reduces the overhead of query parsing and preparation on repeated executions. This results in improved performance, as execution paths are pre-determined, and enhances security by minimizing SQL injection vulnerabilities due to pre-set parameters .

Loading a driver class using Class.forName() ensures that the driver is registered with the DriverManager, allowing the driver to establish the necessary network protocols and compile SQL commands for communication between the application and the database. This step is crucial, as without loading the driver class, the application cannot establish a connection, resulting in execution failure .

To establish a database connection using JDBC with Oracle in Java, first load the driver class using Class.forName('oracle.jdbc.driver.OracleDriver'). Then use the DriverManager to get a connection: Connection con = DriverManager.getConnection('jdbc:oracle:thin:@localhost:1521:xe', 'system', 'root') where 'system' is the username, 'root' is the password, and the URL specifies the Oracle JDBC driver .

You might also like