java
Copy code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class JDBCPreparedStatementExample {
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "user",
"password");
PreparedStatement pstmt = con.prepareStatement("INSERT INTO books (title, author) VALUES (?, ?)");
pstmt.setString(1, "Java Programming");
pstmt.setString(2, "Author Name");
pstmt.executeUpdate();
System.out.println("Data inserted successfully");
} catch (Exception e) {
System.out.println(e);
}
}
}
Set Up Your Database:
Ensure you have a MySQL server running on localhost with a database named testdb.
Create a books table with at least a title column:
sql
Copy code
CREATE TABLE books (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL
);
Compile the java code in cmd and expected output
Data inserted successfully
[OR]
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class App {
public static void main(String[] args) {
// Database connection details
String url = "jdbc:mysql://localhost:3306/testdb"; // Replace with your DB name
String user = "root"; // Replace with your DB username
String password = "Varun13@"; // Replace with your DB password
// SQL queries
String insertQuery = "INSERT INTO books (title, author) VALUES (?, ?)";
String updateQuery = "UPDATE books SET author = ? WHERE id = ?";
String deleteQuery = "DELETE FROM books WHERE id = ?";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
System.out.println("Connected to the database!");
// INSERT operation
try (PreparedStatement insertStmt = conn.prepareStatement(insertQuery)) {
insertStmt.setString(1, "John Doe");
insertStmt.setString(2, "john.doe@example.com");
int rowsInserted = insertStmt.executeUpdate();
System.out.println(rowsInserted + " row(s) inserted.");
}
// UPDATE operation
try (PreparedStatement updateStmt = conn.prepareStatement(updateQuery)) {
updateStmt.setString(1, "john.newemail@example.com");
updateStmt.setInt(2, 1); // Assuming user with ID 1 exists
int rowsUpdated = updateStmt.executeUpdate();
System.out.println(rowsUpdated + " row(s) updated.");
}
// DELETE operation
try (PreparedStatement deleteStmt = conn.prepareStatement(deleteQuery)) {
deleteStmt.setInt(1, 1); // Assuming user with ID 1 exists
int rowsDeleted = deleteStmt.executeUpdate();
System.out.println(rowsDeleted + " row(s) deleted.");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}