Advertisement
Guest User

Untitled

a guest
Jan 13th, 2016
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1.  
  2.  
  3. import java.sql.*;
  4.  
  5. public class Driver {
  6.  
  7. public static void main(String[] args) throws SQLException {
  8.  
  9. Connection myConn = null;
  10. PreparedStatement myStmt = null;
  11. ResultSet myRs = null;
  12.  
  13. try {
  14. // 1. Get a connection to database
  15. myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo", "root" , "");
  16.  
  17. // 2. Prepare statement
  18. myStmt = myConn.prepareStatement("select * from employees where salary > ? and department=?");
  19.  
  20. // 3. Set the parameters
  21. myStmt.setDouble(1, 80000);
  22. myStmt.setString(2, "Legal");
  23.  
  24. // 4. Execute SQL query
  25. myRs = myStmt.executeQuery();
  26.  
  27. // 5. Display the result set
  28. display(myRs);
  29.  
  30. //
  31. // Reuse the prepared statement: salary > 25000, department = HR
  32. //
  33.  
  34. System.out.println("\n\nReuse the prepared statement: salary > 25000, department = HR");
  35.  
  36. // 6. Set the parameters
  37. myStmt.setDouble(1, 25000);
  38. myStmt.setString(2, "HR");
  39.  
  40. // 7. Execute SQL query
  41. myRs = myStmt.executeQuery();
  42.  
  43. // 8. Display the result set
  44. display(myRs);
  45.  
  46.  
  47. }
  48. catch (Exception exc) {
  49. exc.printStackTrace();
  50. }
  51. finally {
  52. if (myRs != null) {
  53. myRs.close();
  54. }
  55.  
  56. if (myStmt != null) {
  57. myStmt.close();
  58. }
  59.  
  60. if (myConn != null) {
  61. myConn.close();
  62. }
  63. }
  64. }
  65.  
  66. private static void display(ResultSet myRs) throws SQLException {
  67. while (myRs.next()) {
  68. String lastName = myRs.getString("last_name");
  69. String firstName = myRs.getString("first_name");
  70. double salary = myRs.getDouble("salary");
  71. String department = myRs.getString("department");
  72.  
  73. System.out.printf("%s, %s, %.2f, %s\n", lastName, firstName, salary, department);
  74. }
  75. }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement