Name:- Priyanka Khandu Thadke
Class:-A(CO5I) Roll no:- 60
Practical no:- 20 Write a Program to update and delete records from database table.
Program Code:-
Q.1)Write a program to delete a record from a table.
Code:
package connect;
import java.sql.*;
public class Pr20_ex1
{
public static void main(String args[])
{
try
{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbtest
","root", "bidwai@14");
String a = "select * from stud";
String b = "delete from stud where rollno = 102"; Statement s = con.createStatement();
s.execute(a);
ResultSet r=s.executeQuery(a);
while(r.next())
{
System.out.println(r.getInt(1)+"\t"+r.getString(2)+"\t"+r.getInt(3)+"\t"+r.getInt( 4));
}
int r1= s.executeUpdate(b);
System.out.println("\n"+r1+" row deleted"+"\n");
ResultSet rs=s.executeQuery("select * from stud");
while(rs.next())
{
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getInt(3)+"\
t"+rs.getInt(4));
}
s.close();
con.close();
}
catch (SQLException s)
{
System.out.println("sql error");
}
}
}
Output:
2.Write the output of following JDBC code.
Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class UpdateQuery
{
public static void main(String [] args)
{
try
{
// Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/vrd","root","root");
PreparedStatement st = con
.prepareStatement("update student set rollno=3 where name='Abhishek'");
st.executeUpdate();
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
Output:
Before After
Exercise:
Q.1)Devlop a program to update name of student from jack to john.
Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class Pr20Ex1
{
public static void main(String [] args)
{
try
{
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/vrd","root","root");
PreparedStatement st = con
.prepareStatement("update student3 set name='John' where name='Jack'");
st.executeUpdate();
System.out.println("record updated");
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
Output:
Before After
Q.2)Develop a program to delete all the records from a product whose “price is
greator than 5000”and ID is ”P1234”.
Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class Pr20Ex2
{
public static void main(String [] args)
{
try
{
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/
vrd","root","root");
PreparedStatement st = con
.prepareStatement("delete from products where Price>=5000 and ID='P1234'");
st.executeUpdate();
System.out.println("Product deleted");
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
Output:
Before After