Advertisement
Guest User

Untitled

a guest
Nov 14th, 2016
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.84 KB | None | 0 0
  1. package ua.inf.smart.prestmt;
  2.  
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.sql.*;
  6. import java.util.Calendar;
  7.  
  8. public class PreparingStatements {
  9.  
  10. private static String HOST = "jdbc:mysql://localhost:3306/dreambase";
  11. private static String NAME = "favorite";
  12. private static String PASS = "abracadabra";
  13.  
  14. private static Connection conn;
  15. private static PreparedStatement preStmt;
  16.  
  17. private static final String INSERT_NEW =
  18. "INSERT INTO applications VALUES (?, ?, ?, ?, ?, ?, ?)";
  19. private static final String GET_ALL = "SELECT * FROM applications";
  20. private static final String DELETE = "DELETE FROM applications WHERE id = ?";
  21.  
  22. public static void main(String[] args) {
  23. try {
  24. conn = DriverManager.getConnection(HOST, NAME, PASS);
  25. preStmt = conn.prepareStatement(INSERT_NEW);
  26. preStmt.setInt(1, 2);
  27. preStmt.setString(2, "\"Some title...\"");
  28. preStmt.setString(3, "\"Some description...\"");
  29. preStmt.setFloat(4, 0.57f);
  30. preStmt.setBoolean(5, true);
  31. preStmt.setDate(6, new Date(Calendar.getInstance().getTimeInMillis()));
  32. preStmt.setBlob(7, new FileInputStream("barashka.jpg"));
  33. preStmt.execute();
  34. preStmt = conn.prepareStatement(GET_ALL);
  35. ResultSet resultSet = preStmt.executeQuery();
  36.  
  37. while (resultSet.next()) {
  38. int id = resultSet.getInt("id");
  39. String title = resultSet.getString("title");
  40. String desc = resultSet.getString("description");
  41. float rating = resultSet.getFloat("rating");
  42. boolean published = resultSet.getBoolean("published");
  43. Date date = resultSet.getDate("created");
  44. byte[] icon = resultSet.getBytes("icon");
  45.  
  46. System.out.println(
  47. "id: " + id +
  48. ", Title: " + title +
  49. ", Desc: " + desc +
  50. ", Rating: " + rating +
  51. ", Published: " + published +
  52. ", Date: " + date +
  53. ", Icon.length: " + icon.length
  54. );
  55. }
  56.  
  57. preStmt = conn.prepareStatement(DELETE);
  58. preStmt.setInt(1, 2);
  59. preStmt.executeUpdate();
  60.  
  61. } catch (SQLException e) {
  62. e.printStackTrace();
  63. }
  64. catch (FileNotFoundException e) {
  65. e.printStackTrace();
  66. }
  67. finally {
  68. shutdown();
  69. }
  70. }
  71.  
  72. private static void shutdown() {
  73. try {
  74. if (preStmt != null) {
  75. preStmt.close();
  76. }
  77. if (conn != null) {
  78. conn.close();
  79. }
  80. } catch (SQLException sqlExcept) {}
  81. }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement