0% found this document useful (0 votes)
8 views

java-2-pract-assi_3-&-4

The document provides a comprehensive guide on using PostgreSQL, including starting the server, connecting to databases, creating tables, and executing SQL commands. It also includes Java JDBC programming examples for database operations, such as inserting, modifying, deleting, and displaying records, along with servlet examples for handling HTTP requests. Additionally, it outlines practical assignments related to database management and web application development.

Uploaded by

mashhsk
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

java-2-pract-assi_3-&-4

The document provides a comprehensive guide on using PostgreSQL, including starting the server, connecting to databases, creating tables, and executing SQL commands. It also includes Java JDBC programming examples for database operations, such as inserting, modifying, deleting, and displaying records, along with servlet examples for handling HTTP requests. Additionally, it outlines practical assignments related to database management and web application development.

Uploaded by

mashhsk
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

PostgreSQL

//Start Postgres -
pc@pc-HP-Pro-Tower-280-G9-PCI-Desktop-PC:~$ sudo -i -u postgres
[sudo] password for pc: srv001

//Connect to Postgres-
postgres@pc-HP-Pro-Tower-280-G9-PCI-Desktop-PC:~$ psql
psql (12.17 (Ubuntu 12.17-0ubuntu0.20.04.1))
Type "help" for help.

//Check Version –
Postgres=# SELECT version();
PostgreSQL 12.16 (Ubuntu 12.16-Oubuntu0.20.04.1) on ……………………….

//List of Databases-
Postgres=# \l;

//Switch Table –
Postgres=# \c;

//Terminate Postgres –
Postgres=# \q;

//Create Database -
postgres=# create database pract31;
CREATE DATABASE

//Connect to Database -
postgres=# \c pract31
You are now connected to database "pract31" as user "postgres".

//Create Table -
pract31=# create table project(p_id int primary key, p_name char(34),p_description
char(56),p_status char(34));
CREATE TABLE

//Show the Table Description-


pract31=# \d project;
Table "public.project"
Column | Type | Collation | Nullable | Default
---------------+---------------+-----------+----------+---------
p_id | integer | | not null |
p_name | character(34) | | |
p_description | character(56) | | |
p_status | character(34) | | |
Indexes:
"project_pkey" PRIMARY KEY, btree (p_id)

//Show the Table Content-


pract31=# table project;
p_id | p_name | p_description | p_status
------+------------------------------------+---------------------------------------
1 | ss | sdf | A
(1 row)

1
JDBC Program Run Process

Step 1-
//Check Directory Folder -
pc@pc-HP-Pro-Tower-280-G9-PCI-Desktop-PC:~/Desktop/EXAM$ dir
CSV\ for\ MCS mysql-connector-j-8.3.0 test.class
Delete.class mysql-connector-j-8.3.0.jar test.java
demo.class postgresql-jdbc4-9.2.jar Update.class
demo.java ProjectDisplay.class
Insert.class ProjectDisplay.java

Step 2-
//Export Class Path for choose postgres jar file-
pc@pc-HP-Pro-Tower-280-G9-PCI-Desktop-PC:~/Desktop/EXAM$ export
CLASSPATH=postgresql-jdbc4-9.2.jar:.

Step 3-
//Config Java File -
pc@pc-HP-Pro-Tower-280-G9-PCI-Desktop-PC:~/Desktop/EXAM$ javac ProjectDisplay.java

Step 4-
// Run java File -
pc@pc-HP-Pro-Tower-280-G9-PCI-Desktop-PC:~/Desktop/EXAM$ java ProjectDisplay

Step 2 to Step 4 Execute after every time to some changes in the program.

2
Java – II
Practical Assignment - 3

a) Create a MOBILE table with fields Model_Number, Model_Name, Model_Color,


Sim_Type, Processor Type. Insert values in the table. Write a menu driven program to pass the
Input using Command line argument to perform the following operations on MOBILE
Table. 1. Insert 2. Modify 3. Delete 4. Search 5. View All 6. Exit
All functions are covered such as insert, update, display, delete and exit. For database material use
here mobile.pgsql file

import java.sql.*;
import java.io.*;
class JDBCMenu
{
public static void main(String args[]) throws Exception
{
Statement stmt=null;
ResultSet rs=null;
PreparedStatement ps1=null,ps2=null;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String model_name,model_color;
int model_number,choice;

Class.forName("org.postgresql.Driver");
Connection con=DriverManager.getConnection("jdbc:postgresql://localhost/pract32",
"postgres", "srv001");
stmt=con.createStatement();

if(con!=null)
System.out.println("Connection Successful.......");

do
{
System.out.println("1 : View Records");

3
System.out.println("2 : Insert Record");
System.out.println("3 : Delete Record");
System.out.println("4 : Modify Record");
System.out.println("5 : Search Record");
System.out.println("6 : Exit");
System.out.println("\n Enter your Choice :");
choice=Integer.parseInt(br.readLine());

switch(choice)
{
case 1 :
rs=stmt.executeQuery("select * from mobile1");
while(rs.next())
{
System.out.println("model_number="+rs.getInt(1));
System.out.println("model_name="+rs.getString(2));
System.out.println("model_color="+rs.getString(3));
}
break;

case 2 :
System.out.println("Enter the model_number");
model_number=Integer.parseInt(br.readLine());
System.out.println("Enter model_name");
model_name=br.readLine();
System.out.println("Enter model_color");
model_color=br.readLine();
ps1=con.prepareStatement("Insert into mobile1 values(?,?,?)");
ps1.setInt(1,model_number);
ps1.setString(2,model_name);
ps1.setString(3,model_color);
ps1.executeUpdate();
System.out.println("Records inserted successfully");
break;

4
case 3 :
System.out.println("Enter model_number to be deleted ");
model_number=Integer.parseInt(br.readLine());
stmt.executeUpdate("Delete form mobile1 where
model_number="+model_number);
System.out.println("Record deleted successfully");
break;

case 4 :
System.out.println("Enter the model_number to be modified");
model_number=Integer.parseInt(br.readLine());
System.out.println("Enter model_name");
model_name=br.readLine();
System.out.println("Enter model_color");
model_color=br.readLine();
ps1=con.prepareStatement("Update into mobile1 set
model_name=?,model_color=?,where model_number=?");
ps1.setInt(1,model_number);
ps1.setString(2,model_name);
ps1.setString(3,model_color);
ps1.executeUpdate();
ps1.executeUpdate();
System.out.println("Records inserted successfully");
break;

case 5 :
System.out.println("Enter model_number to be searched");
model_number=Integer.parseInt(br.readLine());

rs=stmt.executeQuery("select * from mobile1 where


model_number="+model_number);
if(rs.next())
{
System.out.print("model_number ="+rs.getInt(1));

5
System.out.println("model_name ="+rs.getString(2));
System.out.println("model_color ="+rs.getString(3));
}
else
System.out.println("mobile not found");
break;
}
}while(choice!=6);
}
}
mobile.pgsql

create table mobile(mno int ,name char(20),color char(20),sim char(20), Battery int, internal int , ram int , pr
char(25));
select * from mobile;

6
b) Write a program to display information about the database and list all the tables in the database.
(Use Database Metadata).
import java.sql.*;
public class Metadata
{
public static void main(String[] args)
{
try
{
// load a driver
Class.forName("org.postgresql.Driver");

// Establish Connection
Connection conn =
DriverManager.getConnection("jdbc:postgresql://localhost/pract312", "postgres", "srv001");
DatabaseMetaData dbmd = conn.getMetaData();
System.out.println("\t-----------------------------------------------------------------------");
System.out.println("\t\tDriver Name : " + dbmd.getDriverName());
System.out.println("\t\tDriver Version : " + dbmd.getDriverVersion());
System.out.println("\t\tUserName : " + dbmd.getUserName());
System.out.println("\t\tDatabase Product Name : " +
dbmd.getDatabaseProductName());
System.out.println("\t\tDatabase Product Version : " +
dbmd.getDatabaseProductVersion());
System.out.println("\t---------------------------------------------------------------------");
String table[] = { "TABLE" };
ResultSet rs = dbmd.getTables(null, null, null, table);
System.out.println("\t\tTable Names:");
while (rs.next())
{
System.out.println(rs.getString("TABLE_NAME"));
}
rs.close();
conn.close();
} // try

7
catch (Exception e)
{
System.out.println(e);
} // catch
}// main
}// metadata

8
C].Write a program to display information about all coumns in the DONOR table using
ResultSetMetaData. for database material use here donor.pgsql file
import java.sql.*;
public class DONOR
{
public static void main(String[] args)
{
try
{
// load a driver
Class.forName("org.postgresql.Driver");

// Establish Connection
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost/pract313", "postgres",
"srv001");

Statement stmt = null;


stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from donor");

ResultSetMetaData rsmd = rs.getMetaData();


System.out.println("\t-------------------------------------------------");

int count = rsmd.getColumnCount();


System.out.println("\t No. of Columns: " + rsmd.getColumnCount());
System.out.println("\t-------------------------------------------------");
for (int i = 1; i <= count; i++)
{
System.out.println("\t\tColumn No : " + i);
System.out.println("\t\tColumn Name : " + rsmd.getColumnName(i));
System.out.println("\t\tColumn Type : " + rsmd.getColumnTypeName(i));
System.out.println("\t\tColumn Display Size : " + rsmd.getColumnDisplaySize(i));
System.out.println();
} // for

9
System.out.println("\t--------------------------------------------------");
rs.close();
stmt.close();
conn.close();
} // try
catch (Exception e)
{
System.out.println(e);
} // catch
}
}
donor.pgsql
-- create table donor(did int, dname char(22),daddr varchar(22));

-- insert into donor VALUES(1,'AAA','zzz');


-- insert into donor VALUES(2,'BBB','yyy');
-- insert into donor VALUES(3,'CCC','xxx');
-- insert into donor VALUES(4,'DDD','www');

SELECT * from donor;

10
Java – II
Practical Assignment - 4

Set A
a) Design a servlet that provides information about a HTTP request from a client, such as IP
address and browser type. The servlet also provides information about the server on which the
servlet is running, such as the operating system type, and the names of currently loaded
servlets.
serverInfo.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class serverInfo extends HttpServlet implements Servlet
{
protected void doGet(HttpServletRequest req,HttpServletResponse res)throws
IOException,ServletException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.println("<html><body><h2>Information about Http Request</h2>");
pw.println("<br>Server Name: "+req.getServerName());
pw.println("<br>Server Port: "+req.getServerPort());
pw.println("<br>Ip Address: "+req.getRemoteAddr());
//pw.println("<br>Server Path: "+req.getServerPath()); pw.println("<br>Client Browser:
"+req.getHeader("User-Agent"));
pw.println("</body></html>");
pw.close();
}
}
Web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<servlet>
<servlet-name>serverInfo</servlet-name>
<servlet-class>ServerInfo</servlet-class>

11
</servlet>
<servlet-mapping>
<servlet-name>serverInfo</servlet-name>
<url-pattern>/server</url-pattern>
</servlet-mapping>
</web-app>

12
c) Write a program to create a Online Book purchase. User must be login and then purchase the book.
Each page should have a page total. The last page should display a total book and bill, which consists
of a page total of what ever the purchase has been done and print the total. (Use HttpSession)
B2.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

public class B2 extends HttpServlet


{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException,
ServletException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String allsub = "";
String lang[] = req.getParameterValues("sub");
for (int i = 0; i < lang.length; i++) {
allsub = allsub + lang[i];
}
Cookie c1 = new Cookie("sub1", allsub);
res.addCookie(c1);
out.println("cookie added with value: " + allsub);
out.println("<br>");
out.close();
}
}
B2.html
<html>
<head>
<title>cookie</title>
</head>
<body>
<form method="get" action="http://localhost:8080/Varient/B2">
<input type="checkbox" name="sub" value="phy" />Physics<br />

13
<input type="checkbox" name="sub" value="chem" />Chemistry<br />
<input type="checkbox" name="sub" value="bio" />Bio<br />
<input type="checkbox" name="sub" value="math" />Math <br />
<br />
<input type="Submit" value="sub" />
<input type="Reset" value="clear" />
</form>
</body>
</html>

14
Set B
a) Design an HTML page which passes customer number to a search servlet. The servlet searches
for the customer number in a database (customer table) and returns customer details if found
the number otherwise display error message.

Customer.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;

public class customer extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse responce) throws
IOException, ServletException {
responce.setContentType("text/html");
PrintWriter out = responce.getWriter();

try {
Scanner sc = new Scanner(System.in);
Connection con = null;

Statement st = null;
ResultSet rs = null;

// load driver
Class.forName("org.postgresql.Driver");

// establish a conn
con = DriverManager.getConnection("jdbc:postgresql://localhost/bcs", "postgres", "");

int cnum = Integer.parseInt(request.getParameter("num"));

st = con.createStatement();
rs = st.executeQuery("select * from cust where id=" + cnum);

while (rs.next()) {
out.println(rs.getString(1) + " " + rs.getString(2) + " " + rs.getInt(3));

out.println("<br>");
}

} catch (Exception e) {
out.println(e);
}

out.close();
}

15
Customer.html
<html>
<body>
<title>Customer Table</title>
<form method="get" action="http://localhost:8080/servlets/customer">
Enter Cust No:<input type="text" name="num" />
<br />
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
customer.pgsql

create table customer(name char(20),address char(20),id int);


select * from customer;

16
b) Design an HTML page containing option buttons (Maths, Physics, Chemistry and Biology) and
buttons submit and reset. When the user clicks submit, the server responds by adding a cookie
containing the selected subject and sends a message back to the client. Program should not
allow duplicate cookies to be written.

<!DOCTYPE html>
<html>
<body>
<form action="Slip21.jsp" method="post">
<input type="checkbox" name="id" value=" Maths ">
<input type="checkbox" name="id" value=" Physics ">
<input type="checkbox" name="id" value=" Chemistry ">
<input type="checkbox" name="id" value=" Biology ">
<input type="submit" name="submit" value="Submit"> <input type="reset" value="Reset">
<%
Cookie c1 = new Cookie("p", " Maths ");
response.addCookie(c1);
Cookie c2 = new Cookie("d", " Physics ");
response.addCookie(c2);
Cookie c3 = new Cookie("s", " Chemistry ");
response.addCookie(c3);
Cookie c4 = new Cookie("sw", " Biology ");
response.addCookie(c4);
%>
</form>
</body> </html>

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<%
Cookie c[] = request.getCookies();
for(int i=0;i < c.length;i++)
{
Cookie c1 = c[i];
out.println("\nName : "+c1.getValue());
} %>

17

You might also like