//Prepared Statement
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Connection;
public class StatementDemo {
public static void main(String[] args) {
String DB_URL = "jdbc:oracle:thin:@//localhost:1521/XE";
String user = "system";
String pass = "1234";
try (Connection conn = DriverManager.getConnection(DB_URL, user, pass)) {
String insertQuery = "INSERT INTO employee(name, salary) VALUES (?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(insertQuery)) {
pstmt.setString(1, "Jack");
pstmt.setDouble(2, 300000);
pstmt.executeUpdate();
System.out.println("Sucessfully Inserted a record");
}
String getQuery = "SELECT * FROM employee WHERE salary > ?";
try (PreparedStatement pstmt = conn.prepareStatement(getQuery)) {
pstmt.setDouble(1, 350000);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
String str = rs.getString("name");
double sal = rs.getDouble("salary");
System.out.println("Employee Name: " + str + ", Salary is: " + sal);
}
}
} catch (SQLException se) {
System.out.println("An error occured");
se.printStackTrace();
}
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter