Statement-(insert,select,update)
Sun Nov 03 2024 19:13:20 GMT+0000 (Coordinated Universal Time)
Saved by
@wtlab
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DatabaseOperations {
public static void main(String[] args) throws ClassNotFoundException {
String jdbcUrl = "jdbc:oracle:thin:@//localhost:1521/XE"; // Corrected URL
String user = "system";
String password = "hari123";
try {
// Load Oracle JDBC Driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// Establish connection
Connection connection = DriverManager.getConnection(jdbcUrl, user, password);
System.out.println("Connection established successfully");
// Create Statement object
Statement statement = connection.createStatement();
// 1. Insert Operation
String insertSQL = "INSERT INTO Users (username, password, email) VALUES ('hari', 'secure@123', 'john@example.com')";
int insertResult = statement.executeUpdate(insertSQL);
System.out.println(insertResult + " row(s) inserted.");
// 2. Select Operation
String selectSQL = "SELECT * FROM Users";
ResultSet rs = statement.executeQuery(selectSQL);
while (rs.next()) {
System.out.println("UserName: " + rs.getString("username") + ", Password: " + rs.getString("password") +
", Email: " + rs.getString("email"));
}
// 3. Update Operation
String updateSQL = "UPDATE Users SET email = 'john_new@example.com' WHERE username = 'john_doe'";
int updateResult = statement.executeUpdate(updateSQL);
System.out.println(updateResult + " row(s) updated.");
// Close the resources
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
content_copyCOPY
Comments