0% found this document useful (0 votes)
23 views12 pages

Assignment 5 CSE 2year 1sem AY 2024 25

Uploaded by

sureshroopa2k15
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)
23 views12 pages

Assignment 5 CSE 2year 1sem AY 2024 25

Uploaded by

sureshroopa2k15
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/ 12

JAVA Assignment-5

Q1. Establishing JDBC Database Connections

Steps to Connect Java Application with Database


Below are the steps that explains how to connect to Database in Java:

Step 1 – Import the Packages


Step 2 – Load the drivers using the forName() method
Step 3 – Register the drivers using DriverManager
Step 4 – Establish a connection using the Connection class object
Step 5 – Create a statement
Step 6 – Execute the query
Step 7 – Close the connections

Java Database Connectivity

Step 1: Import the Packages


Step 2: Loading the drivers
In order to begin with, you first need to load the driver or register it before using it in the
program. Registration is to be done once in your program. You can register a driver in one of two
ways mentioned below as follows:
2-A Class.forName()
Here we load the driver’s class file into memory at the runtime. No need of using new or create
objects. The following example uses Class.forName() to load the Oracle driver as shown below
as follows:

Class.forName(“oracle.jdbc.driver.OracleDriver”);
2-B DriverManager.registerDriver()
DriverManager is a Java inbuilt class with a static member register. Here we call the constructor
of the driver class at compile time. The following example uses
DriverManager.registerDriver()to register the Oracle driver as shown below:

DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())
Step 3: Establish a connection using the Connection class object
After loading the driver, establish connections as shown below as follows:

Connection con = DriverManager.getConnection(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”

Where oracle is the database used, thin is the driver used, @localhost is the IP Address where a
database is stored, 1521 is the port number and xe is the service provider. All 3 parameters above
are of String type and are to be declared by the programmer before calling the function. Use of
this can be referred to form the final code.

Step 4: Create a statement


Once a connection is established you can interact with the database. The JDBCStatement,
CallableStatement, and PreparedStatement interfaces define the methods that enable you to send
SQL commands and receive data from your database.
Use of JDBC Statement is as follows:

Statement st = con.createStatement();

Note: Here, con is a reference to Connection interface used in previous step .

Step 5: Execute the query


Now comes the most important part i.e executing the query. The query here is an SQL Query.
Now we know we can have multiple types of queries. Some of them are as follows:

The query for updating/inserting a table in a database.


The query for retrieving data.
The executeQuery() method of the Statement interface is used to execute queries of retrieving
values from the database. This method returns the object of ResultSet that can be used to get all
the records of a table.
The executeUpdate(sql query) method of the Statement interface is used to execute queries of
updating/inserting.

Step 6: Closing the connections


So finally we have sent the data to the specified location and now we are on the verge of
completing our task. By closing the connection, objects of Statement and ResultSet will be
closed automatically. The close() method of the Connection interface is used to close the
connection. It is shown below as follows:

con.close();

Example:
// Java Program to Establish Connection in JDBC

// Importing database
import java.sql.*;
// Importing required classes
import java.util.*;

// Main class
class Main {

// Main driver method


public static void main(String a[])
{

// Creating the connection using Oracle DB


// Note: url syntax is standard, so do grasp
String url = "jdbc:oracle:thin:@localhost:1521:xe";

// Username and password to access DB


// Custom initialization
String user = "system";
String pass = "12345";

// Entering the data


Scanner k = new Scanner(System.in);

System.out.println("enter name");
String name = k.next();

System.out.println("enter roll no");


int roll = k.nextInt();
System.out.println("enter class");
String cls = k.next();

// Inserting data using SQL query


String sql = "insert into student1 values('" + name
+ "'," + roll + ",'" + cls + "')";

// Connection class object


Connection con = null;

// Try block to check for exceptions


try {

// Registering drivers
DriverManager.registerDriver(
new oracle.jdbc.OracleDriver());

// Reference to connection interface


con = DriverManager.getConnection(url, user,
pass);

// Creating a statement
Statement st = con.createStatement();

// Executing query
int m = st.executeUpdate(sql);
if (m == 1)
System.out.println(
"inserted successfully : " + sql);
else
System.out.println("insertion failed");

// Closing the connections


con.close();
}

// Catch block to handle exceptions


catch (Exception ex) {
// Display message when exceptions occurs
System.err.println(ex);
}
}
}

Q2. Write a short note on ResultSet Interface


Java ResultSet interface is a part of the java.sql package. It is one of the core components of
the JDBC Framework. ResultSet Object is used to access query results retrieved from the
relational databases.

ResultSet maintains cursor/pointer which points to a single row of the query results. Using
navigational and getter methods provided by ResultSet, we can iterate and access database
records one by one. ResultSet can also be used to update data.

Java ResultSet Hierarchy

The above diagram shows the place of ResultSet in the JDBC Framework. ResultSet can be
obtained by executing SQL Query
using Statement, PreparedStatement or CallableStatement.
AutoCloseable, Wrapper are super interfaces of ResultSet. Now we will see how to work with
ResultSet in our Java programs.
ResultSet Example

We will be using MySQL for our example purpose. Use below DB script to create a database and
table along with some records.

package com.journaldev.examples;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;

public class ResultSetDemo {

public static void main(String[] args) {


String query = "select empid, firstname, lastname, dob from tblemployee";
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn =
DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/empdb", "root", "root");
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
Integer empId = rs.getInt(1);
String firstName = rs.getString(2);
String lastName = rs.getString(3);
Date dob = rs.getDate(4);
System.out.println("empId:" + empId);
System.out.println("firstName:" + firstName);
System.out.println("lastName:" + lastName);
System.out.println("dob:" + dob);
System.out.println("");
}
rs.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
stmt.close();
conn.close();
} catch (Exception e) {}
}
}
}
Output:
empId:1
firstName:Mike
lastName:Davis
dob:1998-11-11

empId:2
firstName:Josh
lastName:Martin
dob:1988-10-22

empId:3
firstName:Ricky
lastName:Smith
dob:1999-05-11

Q3. Write a JavaFX program to displaying text and image

//Java program to create a label with images and text


import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import javafx.scene.image.*;
import java.io.*;
public class JavaFX_LableImage extends Application {
// launch the application
public void start(Stage s) throws Exception
{
// set title for the stage
s.setTitle("creating label");

// create a input stream


FileInputStream input = new FileInputStream("E:\\ aits-tpt.jpg");

// create a image
Image i = new Image(input);

// create a image View


ImageView iw = new ImageView(i);

// create a label
Label b = new Label("AITS-TIRUPATI", iw);

// create a Stack pane


StackPane r = new StackPane();

// add password field


r.getChildren().add(b);

// create a scene
Scene sc = new Scene(r, 500, 500);

// set the scene


s.setScene(sc);

s.show();
}

public static void main(String args[])


{
// launch the application
launch(args);
}
}
Compile and run:

Press ctrl+F11 it will display the output

Q4. Explain about Laying out nodes in scene graph

Layouts are the top level container classes that define the UI styles for scene graph objects.
Layout can be seen as the parent node to all the other nodes. JavaFX provides various layout
panes that support different styles of layouts.

Layout Classes

javafx.scene.layout Package provides various classes that represents the layouts. The classes are
described in the table below.

Class Description

Organizes nodes in top, left, right, centre and


BorderPane
the bottom of the screen.

Organizes the nodes in the horizontal rows


FlowPane according to the available horizontal spaces.
Wraps the nodes to the next line if the
horizontal space is less than the total width of
the nodes

Organizes the nodes in the form of rows and


GridPane
columns.

HBox Organizes the nodes in a single row.

Pane It is the base class for all the layout classes.

Organizes nodes in the form of a stack i.e. one


StackPane
onto another

VBox Organizes nodes in a vertical column.

JavaFX BorderPane
BorderPane arranges the nodes at the left, right, centre, top and bottom of the screen. It is
represented by javafx.scene.layout.BorderPane class. This class provides various methods
like setRight(), setLeft(), setCenter(), setBottom() and setTop() which are used to set the
position for the specified nodes. We need to instantiate BorderPane class to create
the BorderPane layout.

Properties

The properties of BorderPane class along with their setter methods are given in the table below.

Type Property Setter Methods Description

Add the node to the


Node Bottom setBottom()
bottom of the screen

Add the node to the


Node Centre setCentre()
centre of the screen

Add the node to the


Node Left setLeft()
left of the screen

Add the node to the


Node Right setRight()
right of the screen

Add the node to the


Node Top setTop()
top of the screen
1. package application;
2. import javafx.application.Application;
3. import javafx.scene.Scene;
4. import javafx.scene.control.Label;
5. import javafx.scene.layout.*;
6. import javafx.stage.Stage;
7. public class Label_Test extends Application {
8.
9. @Override
10. public void start(Stage primaryStage) throws Exception {
11. BorderPane BPane = new BorderPane();
12. BPane.setTop(new Label("This will be at the top"));
13. BPane.setLeft(new Label("This will be at the left"));
14. BPane.setRight(new Label("This will be at the Right"));
15. BPane.setCenter(new Label("This will be at the Centre"));
16. BPane.setBottom(new Label("This will be at the bottom"));
17. Scene scene = new Scene(BPane,600,400);
18. primaryStage.setScene(scene);
19. primaryStage.show();
20. }
21. public static void main(String[] args) {
22. launch(args);
23. }
24.
25. }

Q5. Explain about short note on mouse events


named MouseEvent. It includes actions like mouse clicked, mouse pressed, mouse released,
mouse moved, mouse entered target, mouse exited target, etc.

When mouse event occurs, the top-most node under cursor is picked and the event is delivered to
it through capturing and bubbling phases described at EventDispatcher.

The mouse (pointer's) location is available relative to several coordinate systems: x,y - relative to
the origin of the MouseEvent's node, sceneX,sceneY - relative to to the origin of the Scene that
contains the node, screenX,screenY - relative to origin of the screen that contains the mouse
pointer.

Write a JavaFX program that listens for mouse clicks and displays a message when the left
mouse button is clicked.

//Main.java

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Text;

public class Main extends Application {

public static void main(String[] args) {


launch(args);
}

@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Mouse Click App");

Label clickLabel = new Label("Mouse Click: ");

// Create a VBox to arrange the labels


VBox vbox = new VBox(clickLabel);

// Create a scene
Scene scene = new Scene(vbox, 400, 300);

// Register a mouse clicked event handler


scene.setOnMouseClicked(event -> {
if (event.isPrimaryButtonDown()) {
//System.out.println("Hello\nAlexandra Abramov!");
clickLabel.setText("Mouse Click: Left button clicked");
}
});

primaryStage.setScene(scene);
primaryStage.show();
}
}

we create a JavaFX application with a 'VBox' layout containing a 'Label' component to display
the mouse click status. We then create a scene and register a mouse click event handler. The
event handler checks if the left mouse button (primary button) is clicked and updates the
'clickLabel' accordingly.

Finally when we run the program and left-click the mouse, we will see the message "Mouse
Click: Left button clicked."

Sample Output:

You might also like