Create an application which can demonstrate the use of JDBC for Database Connectivity

This Java program performs the following operations:

  1. Loads JDBC driver
  2. Connects to database
  3. Inserts records using PreparedStatement
  4. Retrieves data from table
  5. Displays inserted records

PreparedStatement is used because:

  • It improves performance
  • Prevents SQL Injection
  • Allows parameterized queries

Use modern JDBC driver.

✔ Table Structure (MySQL)

CREATE TABLE mytable(
name VARCHAR(20),
marks INT,
fees DOUBLE
);

✔ Java Program

import java.sql.*;


public class Preparedstmnt {

public static void main(String[] args) {

try {
// Load Driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Create Connection
Connection cn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test",
"root",
"password");

// Insert Query
String query = "insert into mytable values(?,?,?)";
PreparedStatement ps = cn.prepareStatement(query);

// First Record
ps.setString(1, "pqr1");
ps.setInt(2, 45);
ps.setDouble(3, 145.50);
ps.executeUpdate();
System.out.println("Data Inserted...");

// Second Record
ps.setString(1, "abc1");
ps.setInt(2, 85);
ps.setDouble(3, 195.50);
ps.executeUpdate();
System.out.println("Data Inserted...");

// Select Query
ps = cn.prepareStatement("select * from mytable");
ResultSet res = ps.executeQuery();

System.out.println("\nYour Inserted Data Are...\n");

while (res.next()) {
System.out.println("Value 1 : " + res.getString(1));
System.out.println("Value 2 : " + res.getInt(2));
System.out.println("Value 3 : " + res.getDouble(3));
}

cn.close();

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

✅ Sample Output

Data Inserted...
Data Inserted...

Your Inserted Data Are...

Value 1 : pqr1
Value 2 : 45
Value 3 : 145.5

Value 1 : abc1
Value 2 : 85
Value 3 : 195.5

Output



FAQs

What is PreparedStatement?

A precompiled SQL statement used to execute parameterized queries efficiently and securely.

Advantages

  • Faster execution
  • Prevents SQL Injection
  • Reusable query
  • Easy parameter handling

Post a Comment

0 Comments