0% found this document useful (0 votes)
32 views4 pages

Java SQL Update and Delete Examples

Uploaded by

sanskrutinile06
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)
32 views4 pages

Java SQL Update and Delete Examples

Uploaded by

sanskrutinile06
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

Practical20:

import [Link];
import [Link];
import [Link];

public class UpdateQuery {


public static void main(String[] args) {
try {
[Link]("[Link]"); // Updated driver class
Connection con = [Link](
"jdbc:mysql://localhost:3306/Ddemodatabase", "root",""
);
PreparedStatement st = [Link]("UPDATE student SET roll_no = 3
WHERE name = 'Abhishek'");
[Link]();
[Link]("Record updated successfully.");
} catch (Exception ex) {
[Link](ex);
}
}
}
1. Develop a program to update name of a student from Jack to John.

import [Link];
import [Link];
import [Link];
public class UpdateQuery {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/Ddemodatabase"; // Database URL
String user = "root"; // Database username
String password = ""; // Database password
try {
// Load MySQL JDBC Driver
[Link]("[Link]");
// Establish connection
Connection con = [Link](url, user, password);
// SQL update query to change name from "Jack" to "John"
String query = "UPDATE student SET name = ? WHERE name = ?";
PreparedStatement pstmt = [Link](query);
// Set parameters for the prepared statement
[Link](1, "John");
[Link](2, "Jack");
// Execute the update
int rowsUpdated = [Link]();
// Output the result
if (rowsUpdated > 0) {
[Link]("Successfully updated the name from Jack to John.");
} else {
[Link]("No record found with the name Jack.");
}
2. Develop a program to delete all record for a product whose "price is greater than 500" and
Id is "P1234".

import [Link];
import [Link];
import [Link];

public class UpdateQuery {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/Ddemodatabase"; // Your database name
String user = "root"; // Your database username
String password = ""; // Your database password

try {
[Link]("[Link]");
Connection con = [Link](url, user, password);

// Update or delete query with corrected column name


String query = "DELETE FROM product WHERE product_price > ? AND id = ?";
PreparedStatement pstmt = [Link](query);

[Link](1, 500); // Set the price condition


[Link](2, "P1234"); // Set the id condition

int rowsAffected = [Link]();

if (rowsAffected > 0) {
[Link]("Successfully deleted records where product_price > 500 and id
= 'P1234'.");
} else {
[Link]("No records found matching the criteria.");
}

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

You might also like