0% found this document useful (0 votes)
11 views6 pages

Java Database Connectivity Examples

The document contains Java code examples demonstrating database connectivity using JDBC with Oracle, MySQL, and Microsoft Access. It includes examples of executing SQL queries, using callable statements for stored procedures, and fetching specific records from a result set. Each section provides a brief overview of the connection setup and query execution process for different database systems.

Uploaded by

naryugam
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)
11 views6 pages

Java Database Connectivity Examples

The document contains Java code examples demonstrating database connectivity using JDBC with Oracle, MySQL, and Microsoft Access. It includes examples of executing SQL queries, using callable statements for stored procedures, and fetching specific records from a result set. Each section provides a brief overview of the connection setup and query execution process for different database systems.

Uploaded by

naryugam
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

//Java Application with Oracle database

import [Link].*;

class OracleCon{

public static void main(String args[]){

try{

//step1 load the driver class

[Link]("[Link]");

//step2 create the connection object

Connection con=[Link](

"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

//step3 create the statement object

Statement stmt=[Link]();

//step4 execute query

ResultSet rs=[Link]("select * from emp");

while([Link]())

[Link]([Link](1)+" "+[Link](2)+" "+[Link](3));

//step5 close the connection object

[Link]();

}catch(Exception e){ [Link](e);}


}

//Java Database Connectivity with MySQL

import [Link].*;

class MysqlCon{

public static void main(String args[]){

try{

[Link]("[Link]");

Connection con=[Link](

"jdbc:mysql://localhost:3306/sonoo","root","root");

//here sonoo is database name, root is username and password

Statement stmt=[Link]();

ResultSet rs=[Link]("select * from emp");

while([Link]())

[Link]([Link](1)+" "+[Link](2)+" "+[Link](3));

[Link]();

}catch(Exception e){ [Link](e);}

// Connectivity with Access

// Without fan

import [Link].*;

class Test{

public static void main(String ar[]){


try{

String database="[Link]";//Here database exists in the current directory

String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};

DBQ=" + database + ";DriverID=22;READONLY=true";

[Link]("[Link]");

Connection c=[Link](url);

Statement st=[Link]();

ResultSet rs=[Link]("select * from login");

while([Link]()){

[Link]([Link](1));

}catch(Exception ee){[Link](ee);}

}}

// With dsn

import [Link].*;

class Test{

public static void main(String ar[]){

try{

String url="jdbc:odbc:mydsn";

[Link]("[Link]");
Connection c=[Link](url);

Statement st=[Link]();

ResultSet rs=[Link]("select * from login");

while([Link]()){

[Link]([Link](1));

}catch(Exception ee){[Link](ee);}

}}

// Stored procedure and callable statement

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class CallingProcedure {

public static void main(String args[]) throws SQLException {

//Registering the Driver

[Link](new [Link]());

//Getting the connection

String mysqlUrl = "jdbc:mysql://localhost/sampleDB";

Connection con = [Link](mysqlUrl, "root", "password");

[Link]("Connection established......");
/Preparing a CallableStateement

CallableStatement cstmt = [Link]("{call myProcedure()}");

//Retrieving the result

ResultSet rs = [Link]();

while([Link]()) {

[Link]("Product Name: "+[Link]("Product_Name"));

[Link]("Date of Dispatch: "+[Link]("Date_Of_Dispatch"));

[Link]("Time of Dispatch: "+[Link]("Time_Of_Dispatch"));

[Link]("Location: "+[Link]("Location"));

[Link]();

// Result set

import [Link].*;

class FetchRecord{

public static void main(String args[])throws Exception{

[Link]("[Link]");

Connection
con=[Link]("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

Statement
stmt=[Link](ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);

ResultSet rs=[Link]("select * from emp765");

//getting the record of 3rd row


[Link](3);

[Link]([Link](1)+" "+[Link](2)+" "+[Link](3));

[Link]();

}}

Common questions

Powered by AI

`ResultSet.CONCUR_UPDATABLE` allows modifications to the database row where the cursor currently resides, enabling updates directly through the result set. This feature should be used when applications require bi-directional data interaction, such as real-time data updates from user interfaces, providing capabilities beyond simple data retrieval. It is critical in applications needing dynamic data assimilation and presentation, but caution is advised due to potential concurrency issues and performance overhead .

The JDBC-ODBC Bridge faces several challenges and limitations: It has performance issues due to its two-layer architectural overhead; compatibility problems arise since it requires ODBC configuration on clients, often involving manual DSN setup. It also lacks portability across platforms due to reliance on native ODBC drivers, making it unsuitable for production environments as it's deprecated in later Java versions, limiting modern application development .

The differences in JDBC connection code between MySQL and Oracle relate primarily to the driver and URL structures: For Oracle, the driver is loaded using `Class.forName("oracle.jdbc.driver.OracleDriver")` and the connection URL is of the format `"jdbc:oracle:thin:@localhost:1521:xe"` . For MySQL, the driver is loaded using `Class.forName("com.mysql.jdbc.Driver")` and the connection URL follows `"jdbc:mysql://localhost:3306/sonoo"`, with database-specific differences in hostname and port .

Java applications connect to Microsoft Access databases using the JDBC-ODBC Bridge, specifying the Access Driver with a URL like `"jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}; DBQ=student.mdb; DriverID=22;READONLY=true"` and loading the driver with `Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")` . This approach differs from Oracle and MySQL connections, which use direct JDBC drivers and URLs like `"jdbc:oracle:thin:@..."` and `"jdbc:mysql://..."`. Microsoft Access connection relies on ODBC, often requiring DSN configuration, while Oracle and MySQL connections are direct, using JDBC-specific drivers and syntax .

To retrieve a specific row in a `ResultSet`, use navigation methods like `rs.absolute(int row)` to position the cursor at a specific row, then access data using getter methods. This operation is essential for applications involving direct data manipulation, such as displaying detailed records or transactions, and allows precise control over database interactions and user interface synchronization, important for data-driven business logic implementations .

`Statement` objects are used in Java for executing simple SQL queries without parameters. They are generally less efficient and more prone to SQL injection attacks because queries are compiled at runtime . In contrast, `PreparedStatement` provides better security by allowing developers to set query parameters, preventing injection, and is precompiled, improving performance for repeated queries. `PreparedStatement` is preferred for dynamic queries with parameters .

To establish a connection to an Oracle database in Java, the key steps include: 1) Load the driver class using `Class.forName("oracle.jdbc.driver.OracleDriver")`; 2) Create the connection object with `DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle")`; 3) Create the statement object with `Statement stmt=con.createStatement()`; 4) Execute the query using `ResultSet rs=stmt.executeQuery("select * from emp")`; and 5) Iterate through the results with `rs.next()` and, finally, close the connection `con.close()` .

To execute a stored procedure using JDBC in Java, register the driver with `DriverManager.registerDriver()`, establish a connection using `DriverManager.getConnection()`, prepare a `CallableStatement` with `con.prepareCall("{call myProcedure()}")`, and execute the stored procedure using `cstmt.executeQuery()`. Iterate through the `ResultSet` to retrieve output .

Using a `CallableStatement` in Java offers several advantages when executing SQL stored procedures: it supports input, output, and input/output parameters, making it suitable for complex database operations. This method also allows for pre-compiled execution in the database, improving performance when repeatedly calling the same procedure. It enables clearer code for handling stored procedures compared to assembling SQL strings manually .

`ResultSet.TYPE_SCROLL_SENSITIVE` allows navigation through the result set in both directions, and updates to the database will be reflected in the result set. This capability is crucial for applications that require up-to-date data views while scrolling, allowing real-time data manipulation and reflection of concurrent changes. It is beneficial where data consistency and current state visibility are vital, such as in client-server applications .

You might also like