Practical No.
29
3. Develop JDBC program to retrieve data.
Code
package retrievedataexample;
import [Link];
import [Link];
import [Link];
import [Link];
public class RetrieveDataExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/Students";
String username = "root";
String password = "3367";
String selectQuery = "SELECT id, name, age, grade FROM students";
try {
Connection connection =
[Link]("jdbc:mysql://localhost:3306/Students", "root", "3367");
Statement statement = [Link]();
ResultSet resultSet = [Link](selectQuery);
[Link]("ID\tName\tAge\tGrade");
while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
int age = [Link]("age");
String grade = [Link]("grade");
[Link](id + "\t" + name + "\t" + age + "\t" + grade);
}
[Link]();
[Link]();
[Link]();
} catch (Exception e) {
[Link]();
Output:-
4. Develop a program to update a record in database table
Code
package updaterecordexample;
import [Link];
import [Link];
import [Link];
public class UpdateRecordExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/Students";
String username = "root";
String password = "3367";
String updateQuery = "UPDATE students SET name = ?, age = ?, grade = ? WHERE id = ?";
try {
Connection connection =
[Link]("jdbc:mysql://localhost:3306/Students", "root", "3367");
PreparedStatement preparedStatement = [Link](updateQuery);
[Link](1, "John Doe");
[Link](2, 25);
[Link](3, "A");
[Link](4, 1);
int rowsUpdated = [Link]();
if (rowsUpdated > 0) {
[Link]("Record updated successfully!");
} else {
[Link]("No record found with the given ID.");
[Link]();
[Link]();
} catch (Exception e) {
[Link]();
Output:-