CA-603 ADVANCED JAVA 3 & 4 Marks (BBACA) || Question with answer
1. Explain
various types of JDBC drivers. Discuss advantages and disadvantages
1) JDBC-ODBC bridge driver
The 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. This is now discouraged because of thin driver.
Advantages:
1. easy to use.
2. can be easily connected to any database.
Disadvantages:
1. Performance degraded because JDBC method call is converted into the ODBC
function calls.
2. The ODBC driver needs to be installed on the client machine.
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The
driver converts JDBC method calls into native calls of the database API. It is
not written entirely in java.
Advantage:
1. performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
1. The Native driver needs to be installed on the each client machine.
2. The Vendor client library needs to be installed on client machine.
3) Network Protocol driver
The Network Protocol driver uses middleware (application server) that converts
JDBC calls directly or indirectly into the vendor-specific database protocol.
It is fully written in java
Advantage:
1. No client side library is required because of application server that
can perform many tasks like auditing, load balancing, logging etc.
Disadvantages:
1. Network support is required on client machine.
2. Requires database-specific coding to be done in the middle tier.
3. Maintenance of Network Protocol driver becomes costly because it requires
database-specific coding to be done in the middle tier..
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific
database protocol. That is why it is known as thin driver. It is fully written
in Java language.
Advantage:
1. Better performance than all other drivers.
2. No software is required at client side or server side.
Disadvantage:
1. Drivers depend on the Database.
2. What
is a difference between a connection and statement?
Statement
|
PreparedStatement
|
It
is used when SQL query is to be executed only once.
|
It
is used when SQL query is to be executed multiple times.
|
You
can not pass parameters at runtime.
|
You
can pass parameters at runtime.
|
Used
for CREATE, ALTER, DROP statements.
|
Used
for the queries which are to be executed multiple times.
|
Performance
is very low.
|
Performance
is better than Statement.
|
It
is base interface.
|
It
extends statement interface.
|
Used
to execute normal SQL queries.
|
Used
to execute dynamic SQL queries.
|
We
can not use statement for reading binary data.
|
We
can use Preparedstatement for reading binary data.
|
It
is used for DDL statements.
|
It
is used for any SQL Query.
|
We
can not use statement for writing binary data.
|
We
can use Preparedstatement for writing binary data.
|
No
binary protocol is used for communication.
|
Binary
protocol is used for communication.
|
3. Explain
how to create the URL
The easiest way to create a URL object is from a String that represents the
human-readable form of the URL address. This is typically the form that another
person will use for a URL. For example, the URL for the Gamelan site, which is
a directory of Java resources, takes the following form:
In your Java program, you can use a String containing this text to create a URL
object:
URL gamelan = new URL("http://www.gamelan.com/");
The URL object created above represents an absolute URL. An absolute URL
contains all of the information necessary to reach the resource in question.
You can also create URL objects from a relative URL address.
4.Explain
the significance of each:
a. ResultSet
ResultSet interface represents the result set of a database query. A ResultSet
object maintains a cursor that points to the current row in the result set. The
term "result set" refers to the row and column data contained in a
ResultSet object. Navigational methods − Used to move the cursor around.
b. ResultSetMetaData
The ResultSetMetaData provides information about the obtained ResultSet object
like, the number of columns, names of the columns, datatypes of the columns,
name of the table etc… Following are some methods of ResultSetMetaData class.
c. DatabaseMetaData
Data about data is known as metadata. The DatabaseMetaData interface provides
methods to get information about the database you have connected with like,
database name, database driver version, maximum column length etc... Following
are some methods of DatabaseMetaData class.
5. Which
to use and when?
a. execute()
This method is used to execute SQL DDL statements, it returns a boolean value
specifying weather the ResultSet object can be retrieved.
b. executeUpdate()
This method is used to execute statements such as insert, update, delete. It
returns an integer value representing the number of rows affected.
c. executeQuery()
This method is used to execute statements that returns tabular data (example
select). It returns an object of the class ResultSet.
d. Statement
e. CallabaleStatement
The CallableStatement interface provides methods to execute the stored
procedures. Since the JDBC API provides a stored procedure SQL escape syntax,
you can call stored procedures of all RDBMS in single standard way.
f. PreparedStatement.
A PreparedStatement is a pre-compiled SQL statement. It is a subinterface of
Statement. Prepared Statement objects have some useful additional features than
Statement objects. Instead of hard coding queries, PreparedStatement object
provides a feature to execute a parameterized query.
6. By
considering PreparedStatement interface, explain following methods of it
a. setString()
b. setInt()
7. what
record is the cursor initially positioned in the ResultSet?
Whenever we execute SQL statements using the executeQuery() method, it returns
a ResultSet object which holds the tabular data returned by the SELECT
queries(in general).
The ResultSet object contains a cursor/pointer which points to the current row.
Initially this cursor is positioned before first row (default position).
You can move the cursor of the ResultSet object to the first row from the
current position, using the first() method of the ResultSet interface.
rs.first()
This method returns a boolean value specifying whether the cursor has been
moved to the first row successfully.
If there are no rows in the current ResultSet object this method returns false,
else it returns true.
8. Write
a small program to open a connection to a database.
import java.sql.*;
public class connection{
Connection con = null;
public static Connection connectDB()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection(
"jdbc:mysql://localhost:3306/database",
"root",
"1234");
return con;
}
catch (SQLException |
ClassNotFoundException e)
{
System.out.println(e);
return null;
}
}
}
9. Describe
JDBC-ODBC Bridge in detail.
The 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. This is now discouraged because of thin driver.
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends
that you use JDBC drivers provided by the vendor of your database instead of
the JDBC-ODBC Bridge.
Advantages:
easy to use.
can be easily connected to any database.
Disadvantages:
Performance degraded because JDBC method call is converted into the ODBC
function calls.
The ODBC driver needs to be installed on the client machine.
10. Explain
architecture of JDBC in detail.
If you want to develop a Java application that communicates with a database,
you should use JDBC API. A driver is the implementation of the said API;
various vendors provide various drivers, you need to use a suitable driver with
respect to the database you need to communicate with. The driver manager loads
the driver and manages the driver.
Following are the components of JDBC:
JDBC DriverManager: The
DriverManager class of the java.sql package manages different types of JDBC
drivers. This class loads the driver classes. In addition to this whenever a
new connection establishes it chooses and loads the suitable driver from the
previously loaded ones.
JDBC API: It is a Java abstraction
which enables applications to communicate with relational databases. It
provides two main packages namely, java.sql and javax.sql. It provides classes
and methods to connect with a database, create statements (quires), execute
statements and handle the results.
11.How to
connect Java application to PostgresSQL? Explain with example.
package net.codejava.jdbc; import java.sql.Connection;
import java.sql.DriverManager; import java.sql.SQLException;
import java.util.Properties; public class JdbcPostgresqlConnection {
public static void main(String[]
args) {
Connection conn1 = null; Connection conn2 = null;
Connection conn3 = null; try {
String dbURL1 =
“jdbc:postgresql:ProductDB1?user=root&password=secret";
conn1 =
DriverManager.getConnection(dbURL1);
if (conn1 != null) {
System.out.println("Connected to database #1");
}
String dbURL2 =
"jdbc:postgresql://localhost/ProductDB2";
String user =
"root";
String pass =
"secret";
conn2 =
DriverManager.getConnection(dbURL2, user, pass);
if (conn2 != null) {
System.out.println("Connected to database #2");
}
String dbURL3 =
"jdbc:postgresql://localhost:5432/ProductDB3";
Properties parameters = new
Properties();
parameters.put("user", "root");
parameters.put("password", "secret");
conn3 = DriverManager.getConnection(dbURL3,
parameters);
if (conn3 != null) {
System.out.println("Connected to database #3");
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally { try {
if (conn1 != null
&& !conn1.isClosed()) {
conn1.close();
} if (conn2 != null &&
!conn2.isClosed()) {
conn2.close();
} if (conn3 != null &&
!conn3.isClosed()) {
conn3.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
} } }}
12. Explain
thread life cycle in detail.
New: Whenever a new thread is
created, it is always in the new state. For a thread in the new state, the code
has not been run yet and thus has not begun its execution.
Active: When a thread invokes the
start() method, it moves from the new state to the active state. The active
state contains two states within it: one is runnable, and the other is running.
Runnable: A thread, that is ready to
run is then moved to the runnable state. In the runnable state, the thread may
be running or may be ready to run at any given instant of time. It is the duty
of the thread scheduler to provide the thread time to run, i.e., moving the
thread the running state.
Running: When the thread gets the
CPU, it moves from the runnable to the running state. Generally, the most
common change in the state of a thread is from runnable to running and again
back to runnable.
Blocked or Waiting: Whenever a
thread is inactive for a span of time (not permanently) then, either the thread
is in the blocked state or is in the waiting state.
Timed Waiting: Sometimes, waiting
for leads to starvation. For example, a thread (its name is A) has entered the
critical section of a code and is not willing to leave that critical section.
In such a scenario, another thread (its name is B) has to wait forever, which
leads to starvation.
Terminated: A thread reaches the
termination state because of the following reasons:
1. When a thread has finished its job, then it exists or terminates normally.
2. Abnormal termination: It occurs
when some unusual events such as an unhandled exception or segmentation fault.
13. Explain
the thread priorities with an example.
Setter & Getter Method of Thread
Priority
public final int getPriority(): The java.lang.Thread.getPriority() method
returns the priority of the given thread.
public final void setPriority(int
newPriority): The java.lang.Thread.setPriority() method updates or assign
the priority of the thread to newPriority. The method throws
IllegalArgumentException if the value newPriority goes out of the range, which
is 1 (minimum) to 10 (maximum).
3 constants defined in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is
1 and the value of MAX_PRIORITY is 10.
Example :
import java.lang.*;
public class ThreadPriorityExample extends Thread
{
public void run()
{
System.out.println("Inside the run() method");
}
public static void main(String argvs[])
{
ThreadPriorityExample th1 = new ThreadPriorityExample();
ThreadPriorityExample th2 = new ThreadPriorityExample();
ThreadPriorityExample th3 = new ThreadPriorityExample();
System.out.println("Priority of the thread th1 is : " +
th1.getPriority());
System.out.println("Priority of the thread th2 is : " +
th2.getPriority());
System.out.println("Priority of the thread th2 is : " +
th2.getPriority());
th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);
System.out.println("Priority of the thread th1 is : " +
th1.getPriority());
System.out.println("Priority of the thread th2 is : " +
th2.getPriority());
System.out.println("Priority of the thread th3 is : " +
th3.getPriority());
System.out.println("Currently Executing The Thread : " +
Thread.currentThread().getName());
System.out.println("Priority of the main thread is : " +
Thread.currentThread().getPriority());
Thread.currentThread().setPriority(10);
System.out.println("Priority of the main thread is : " +
Thread.currentThread().getPriority()); }}
14.Explain
with suitable diagram the HTTP communication between Web client and Web server
Key Points
1.
When client sends request for a web page, the web server search for the
requested page if requested page is found then it will send it to client with
an HTTP response.
2. If the requested web page is not found, web server will the send an HTTP
response:Error 404 Not found.
3. If client has requested for some other resources then the web server will
contact to the application server and data store to construct the HTTP
response.
15. What
is Client Server Model?
Client: When we talk the word
Client, it mean to talk of a person or an organization using a particular
service. Similarly in the digital world a Client is a computer (Host) i.e.
capable of receiving information or using a particular service from the service
providers (Servers).
Servers: Similarly, when we talk the
word Servers, It mean a person or medium that serves something. Similarly in
this digital world a Server is a remote computer which provides information
(data) or access to particular services.
How the browser interacts with the
servers ?
There are few steps to follow to interacts with the servers a client.
1. User enters the URL(Uniform Resource Locator) of the website or file. The Browser
then requests the DNS(DOMAIN NAME SYSTEM) Server.
2. DNS Server lookup for the address of the WEB Server.
3. DNS Server responds with the IP address of the WEB Server.
4. Browser sends over an HTTP/HTTPS request to WEB Server’s IP (provided by DNS
server).
16.Write
short note on URL Programming.
URL is an acronym for Uniform Resource Locator and is a reference (an address)
to a resource on the Internet.
A URL has two main components:
Protocol identifier: For the URL http://example.com, the protocol
identifier is http.
Resource name: For the URL
http://example.com, the resource name is example.com.
Note that the protocol identifier and the resource name are separated by a
colon and two forward slashes. The protocol identifier indicates the name of
the protocol to be used to fetch the resource. The example uses the Hypertext
Transfer Protocol (HTTP), which is typically used to serve up hypertext
documents. HTTP is just one of many different protocols used to access
different types of resources on the net. Other protocols include File Transfer
Protocol (FTP), Gopher, File, and News.
The resource name is the complete address to the resource. The format of the
resource name depends entirely on the protocol used, but for many protocols,
including HTTP, the resource name contains one or more of the following
components:
Host Name The name of the machine on
which the resource lives.
Filename The pathname to the file on
the machine.
Port Number The port number to which
to connect (typically optional).
Reference A reference to a named
anchor within a resource that usually identifies a specific location within a
file (typically optional).
17. Explain
TCP/IP client sockets with suitable example.
TCP/IP client sockets. TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-to
point, stream-based connections between hosts on the internet. A socket can be
used to connect java'sI/Osystem to other programs that may reside either on the
local machine or on any other machine on the internet.
Example :
Example program client socket
Import java.net.*;
Import java.io.*;
Public class clientprogram(
Private Socket socket=null;
Private datainputstream input=null;
Private dataoutputstream output=null;
Public client(string address,int port){
Try{
Socket new socket(address,port);
Sop("connected");
Input=new datainputstream(system.in);
Out-new dataoutputstream(socket.getoutputstream());}
Catch(unknownHostExceptionu){
Sop(u);}
Catch(IOExceptioni){
Sop(i);}
String line=""";
While(!line.equals('over')){
Try{
Line-input.readline();
Out.writeUTF(line);
Catch(IOException
Sop(i);}}
Try
{input.close();
Out.close();
Socket.close();}
}
i){
Catch(IOExceptioni){
Sop(i);}}
Public static voidn=amin(stringargs[]){
Client client=new client(127.0.0.1",5000);}}
18.Explain
TCP/IP server sockets with suitable example.
1. A socket in java is one endpoint of two-way communication link between two
programs running on the network.
2. A socket is bound to a port number so that the TCP layer can identify the
application that data is destined to be sent to.
3. An endpoint is a combination of an IP address and a port number.
Example :
Import java.net.*;
Import java.io.*;
Public class serverside{
Private Socket socket=null;
Private serversocket=null;
Sop("server started");
Sop("waiting for client");
Socket-server.accept();
Sop("client accepted");
In-new dataintputstream(
New bufferedinputstream(socket.getInputstream());
String line="";
While(!line.equals("over")){
Try{
Line-input.readline();
Out.writeUTF(line);}
Catch(IOExceptioni){
Sop(i);}}
Sop("closing connection");
Socket.close();
In.close();}
Catch(IOExceptioni){
Sop(i);}}
Public static void main(stringargs[]){
Server server=new server(5000);}}
19.Explain
UDP Server sockets with suitable example.
UDP also allows two (or more) processes running on different hosts to
communicate. However, UDP differs from TCP in many fundamental ways. First, UDP
is a connectionless service -- there isn't an initial handshaking phase during
which a pipe is established between the two processes. Because UDP doesn't have
a pipe, when a process wants to send a batch of bytes to another process, the
sending process must exclude attach the destination process's address to the
batch of bytes. And this must be done for each batch of bytes the sending
process sends.
Example :
import java.io.*;
import java.net.*;
class UDPClient {
public static void main(String
args[]) throws Exception
{
BufferedReader inFromUser =
new BufferedReader(new
InputStreamReader(System.in));
DatagramSocket clientSocket = new
DatagramSocket();
InetAddress IPAddress =
InetAddress.getByName("hostname");
byte[] sendData = new byte[1024];
byte[] receiveData = new
byte[1024];
String sentence =
inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData,
sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket =
new DatagramPacket(receiveData,
receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence =
new
String(receivePacket.getData());
System.out.println("FROM
SERVER:" + modifiedSentence);
clientSocket.close();
}
}
20.What
is a servlet? Explain the lifecycle of servlet in detail.
A servlet life cycle can be defined as the entire process from its creation
till the destruction. The following are the paths followed by a servlet.
1. The servlet is initialized by calling the init() method.
2. The servlet calls service() method to process a client's request.
3. The servlet is terminated by calling the destroy() method.
4. Finally, servlet is garbage collected by the garbage collector of the JVM.
The init() Method
The init method is called only once. It is called only when the servlet is
created, and not called for any user requests afterwards. So, it is used for
one-time initializations, just as with the init method of applets.
The service() Method
The service() method is the main method to perform the actual task. The
servlet container (i.e. web server) calls the service() method to handle
requests coming from the client( browsers) and to write the formatted response
back to the client.
Each time the server receives a request for a servlet, the server spawns a new
thread and calls service. The service() method checks the HTTP request type
(GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc.
methods as appropriate.
The doGet() Method
A GET request results from a normal request for a URL or from an HTML form
that has no METHOD specified and it should be handled by doGet() method.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
The doPost() Method
A POST request results from an HTML form that specifically lists POST as
the METHOD and it should be handled by doPost() method.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{}
The destroy() Method
The destroy() method is called only once at the end of the life cycle of a
servlet. This method gives your servlet a chance to close database connections,
halt background threads, write cookie lists or hit counts to disk, and perform
other such cleanup activities.
Architecture Diagram
The following figure depicts a typical servlet life-cycle scenario. First
the HTTP requests coming to the server are delegated to the servlet container.
The servlet container loads the servlet before invoking the service() method.
Then the servlet container handles multiple requests by spawning multiple
threads, each thread executing the service() method of a single instance of the
servlet.
21.Explain
HTTPRequest and HTTPResponse.
HTTP Request
HTTP Requests are messages which are sent by the client or user to initiate an
action on the server.
The first line of the message includes the request message from the client to
the server, the method which is applied to the resource, identifier of the
resource, and the protocol version.
Syntax
Request = Request-Line
*(( general-header
| request-header
| entity-header )
CRLF)
CRLF
[ message-body ]
Request Line: The Request-Line
starts with a method token, which is followed by the Request-URI, the protocol
version, and ending with CRLF. Using the SP characters, the elements are
separated.
HTTP Response
HTTP Response sent by a server to the client. The response is used to
provide the client with the resource it requested. It is also used to inform
the client that the action requested has been carried out.
Status Line Response Header Fields
or a series of HTTP headers
Message Body In the request message,
each HTTP header is followed by a carriage returns line feed (CRLF). After the
last of the HTTP headers, an additional CRLF is used and then begins the
message body.
Status Line In the response message,
the status line is the first line. The status line contains three items:
a) HTTP Version Number It is used to
show the HTTP specification to which the server has tried to make the message
comply.
b) Status Code It is a three-digit
number that indicates the result of the request. The first digit defines the
class of the response. The last two digits do not have any categorization role.
There are five values for the first digit, which are as follows:
c) Reason Phrase It is also known as
the status text. It is a human-readable text that summarizes the meaning of the
status code.
Response Header Fields The HTTP
Headers for the response of the server contain the information that a client
can use to find out more about the response, and about the server that sent it.
Message Body The response's message
body may be referred to for convenience as a response body.
22.Explain
the lifecycle of JSP in detail.
JSP Compilation
When a browser asks for a JSP, the JSP engine first checks to see whether
it needs to compile the page.
The compilation process involves three steps −
1. Parsing the JSP.
2. Turning the JSP into a servlet.
3. Compiling the servlet.
4. JSP Initialization
When a container loads a JSP it invokes the jspInit() method before servicing
any requests.
Typically, initialization is performed only once and as with the servlet init
method, you generally initialize database connections, open files, and create
lookup tables in the jspInit method.
JSP Execution
This phase of the JSP life cycle represents all interactions with requests
until the JSP is destroyed.
Whenever a browser requests a JSP and the page has been loaded and initialized,
the JSP engine invokes the _jspService() method in the JSP.
JSP Cleanup
The destruction phase of the JSP life cycle represents when a JSP is being
removed from use by a container.
The jspDestroy() method is the JSP equivalent of the destroy method for
servlets. Override jspDestroy when you need to perform any cleanup, such as
releasing database connections or closing open files.
23.State the purpose of implicit objects. Explain
any four implicit objects.
Purpose :
These Objects are the Java objects that the JSP Container makes available to
the developers in each page and the developer can call them directly without
being explicitly declared. JSP Implicit Objects are also called pre-defined
variables.
S.No.
|
Object & Description
|
1
|
request
This is
the HttpServletRequest object associated with the request.
|
2
|
response
This is
the HttpServletResponse object associated with the response to
the client.
|
3
|
out
This is
the PrintWriter object used to send output to the client.
|
4
|
Session
This is
the HttpSession object associated with the request.
|
24.Explain
hibernate architecture?
The Hibernate architecture includes many objects such as persistent object,
session factory, transaction factory, connection factory, session, transaction
etc.
The Hibernate architecture is
categorized in four layers.
1. Java application layer
2. Hibernate framework layer
3. Backhand api layer
4. Database layer
25.What
is the difference between get and load method?
Get()
|
Load()
|
It
is used to fetch data from the database for the given identifier
|
It
is also used to fetch data from the database for the given
identifier
|
It
object not found for the given identifier then it will return null
object
|
It will
throw object not found exception
|
It
returns fully initialized object so this method eager load the object
|
It
always returns proxy object so this method is lazy load the object
|
It is
slower than load() because it return fully initialized object which impact
the performance of the application
|
It is
slightly faster.
|
If you
are not sure that object exist then use get() method
|
If you
are sure that object exist then use load() method
|
26.What
is the difference between update and merge method?
merge()
|
update()
|
A merge() method is
used to update the database. It will also update the database if the object
already exists.
|
An update() method
only saves the data in the database. If the object already exists, no update
is performed.
|
It will update the
object in the database without any exception.
|
When creating a
detached object into persistent state, it will throw an exception only when
the Session contains a persistent object with the same primary key.
|
27.What
are the inheritance mapping strategies?
We can map the inheritance hierarchy classes with the table of the database. There are three inheritance mapping
strategies defined in the hibernate:
1. Table Per Hierarchy 2. Table Per Concrete class 3. Table Per Subclass
Table Per Hierarchy In table per
hierarchy mapping, single table is required to map the whole hierarchy, an
extra column (known as discriminator column) is added to identify the class.
But nullable values are stored in the table.
Table Per Concrete class In case of
table per concrete class, tables are created as per class. But duplicate column
is added in subclass tables.
Table Per Subclass In this strategy,
tables are created as per class but related by foreign key. So there are no
duplicate columns.
28.Write
a JSP Program to accept user and check whether it is prime or not.
<!DOCTYPE>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<%
int number=Integer.parseInt(request.getParameter("id"));
int flag=0;
for(int i=2;i<=(number-1);i++)
{
if(number%i==0)
{
flag=1;
break;
}
}
if(flag==0)
{
out.println("Prime
Number");
}
else
{
out.println("Not a Prime
Number");
}
%>
</body>
</html>
29.Write
a JDBC Program to Insert the record into patient table (use prepared
Statement).
import java.sql.*;
import java.util.*;
public class prepareDemo
{
public static void main(String args[])
throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =
DriverManager.getConnection("jdbc:odbc:dsn1",
"system");
PreparedStatement pstmt =
con.prepareStatement("insert into
patienttable(patno,patname,patromm) values(?,?,?)");
Scanner sc = new
Scanner(System.in);
System.out.print("Enter the
Patient Number : ");
int patno = sc.nextInt();
System.out.print("Enter the
Patient Name : ");
String patname = sc.next();
System.out.print("Enter the
Patient Room : ");
int patroom = sc.nextInt();
pstmt.setInt(1, patno);
pstmt.setString(2, patname);
pstmt.setInt(3, patroom);
pstmt.executeUpdate();
System.out.println("record
inserted");
con.close();
}
}
3 Marks Question
Question 5.
1.
MetaData
Metadata in Java is used to know the data about data. It means for example
table field names, field data type, field data type length, database table
names, number of databases that existed in the specific database, etc.
2.
Statement
a statement is an executable instruction that tells the compiler what to
perform. It forms a complete command to be executed and can include one or more
expressions. A sentence forms a complete idea that can include one or more
clauses.
3.
Callable
Statement
CallableStatement interface is used to call the stored procedures and
functions. We can have business logic on the database by the use of stored
procedures and functions that will make the performance better because these
are precompiled. Suppose you need the get the age of the employee based on the
date of birth, you may create a function that receives date as the input and
returns age of the employee as the output.
4.
Prepared
Statement
The PreparedStatement interface is a subinterface of Statement. It is used to
execute parameterized query.
Let's see the example of parameterized query:
String sql="insert into emp values(?,?,?)";
As you can see, we are passing parameter (?) for the values. Its value will be
set by calling the setter methods of PreparedStatement.
5.
Multithreading
Multithreading refers to a process of executing two or more threads
simultaneously for maximum utilization of the CPU. A thread in Java is a
lightweight process requiring fewer resources to create and share the process
resources.
6.
Thread
A thread in Java is the direction or path that is taken while a program is
being executed. Generally, all the programs have at least one thread, known as
the main thread, that is provided by the JVM or Java Virtual Machine at the
starting of the program's execution.
7.
Synchronization
Synchronization in java is the capability to control the access of multiple
threads to any shared resource. In the Multithreading concept, multiple threads
try to access the shared resources at a time to produce inconsistent results.
The synchronization is necessary for reliable communication between threads.
8.
Web
Browser
web Browser is an application software that allows us to view and explore
information on the web. User can request for any web page by just entering a
URL into address bar. Web browser can show text, audio, video, animation and
more. It is the responsibility of a web browser to interpret text and commands
contained in the web page. Earlier the web browsers were text-based while now a
days graphical-based or voice-based web browsers are also available.
9.
Web
server
Web pages are a collection of data, including images, text files, hyperlinks,
database files etc., all located on some computer (also known as server space)
on the Internet. A web server is dedicated software that runs on the server-side.
When any user requests their web browser to run any web page, the webserver
places all the data materials together into an organized web page and forwards
them back to the web browser with the help of the Internet.
10.
Protocol
A protocol is a set of rules basically that is followed for communication. For example:
TCP
FTP
Telnet
SMTP
POP etc.
11.
HTTP
The Hypertext Transfer Protocol (HTTP) is a protocol (a set of rules that
describes how information is exchanged) that allows a client (such as a web
browser) and a web server to communicate with each other. HTTP is based on a
request-response model.
12.
Home
Page
It is the name of a website's main page, which acts as the site's beginning
point and where visitors can find links to other pages on the site. For
example, when you visit https://javatpoint.com, you will visit the Javatpoint
home page directly. On all web servers, the homepage is index.
13.
Fire
wall
A firewall controls the flow of data between two or more networks, and manages the
links between the networks. A firewall can consist of both hardware and
software elements.
14.
Proxy
server
Proxy servers act as intermediaries between client applications and other
servers. In an enterprise setting, we often use them to help provide control
over the content that users consume, usually across network boundaries. In this
tutorial, we'll look at how to connect through proxy servers in Java.
15.
PORT
The port number is used to identify different applications uniquely. The port
number behaves as a communication endpoint among applications. The port number
is correlated with the IP address for transmission and communication among two
applications. There are 65,535 port numbers, but not all are used every day.
16.
URL
URL stands for Uniform Resource Locator and represents a resource on the World
Wide Web, such as a Web page or FTP directory. This section shows you how to
write Java programs that communicate with a URL. A URL can be broken down into
parts, as follows − protocol://host:port/path?
17.
Servlet
If you like coding in Java, then you will be happy to know that using Java
there also exists a way to generate dynamic web pages and that way is Java
Servlet. But before we move forward with our topic let’s first understand the
need for server-side extensions.Servlets are the Java programs that run on the
Java-enabled web server or application server. They are used to handle the
request obtained from the webserver, process the request, produce the response,
then send a response back to the webserver.
18.
Session
In simpler terms, a session is a state consisting of several requests and
response between the client and the server. It is a known fact that HTTP and
Web Servers are both stateless. Hence, the only way to maintain the state of
the user is by making use of technologies that implement session tracking.
19.
Cookies
a cookie, a small amount of information sent by a servlet to a Web browser,
saved by the browser, and later sent back to the server. A cookie's value can
uniquely identify a client, so cookies are commonly used for session
management.
20.
Scriptlet
The scripting elements provides the ability to insert java code inside the jsp.
There are three types of scripting elements:
scriptlet tag
1. expression tag
2. declaration tag
3. JSP scriptlet tag
A scriptlet tag is used to execute java source code in JSP.
Syntax is as follows:
<% java source code %>
2 Comments
Hello sir, thank you for the questions and solutions. I have a request to you, would you please upload the Android programming 2 and 4 Mark's question and answers
ReplyDeleteSir can you please provide us dot net framework question bank
ReplyDelete