Guest User

Untitled

a guest
Dec 4th, 2018
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.03 KB | None | 0 0
  1. class MariaDB extends PhoneBookModel{
  2.  
  3. private static final String dbClassName = "org.mariadb.jdbc.Driver";
  4. private static final String CONNECTION = "jdbc:mariadb://localhost:3306/test";
  5. private final String USER = "root";
  6. private final String PASS = "123456";
  7.  
  8.  
  9. public MariaDB(PhoneBookView view){
  10. super(view);
  11. }
  12. public void save(){
  13. Connection conn = null;
  14. Statement stmt = null;
  15. try {
  16. Class.forName(dbClassName);
  17. // System.out.println("Connecting to a selected database...");
  18. conn = DriverManager.getConnection(CONNECTION, USER, PASS);
  19. // System.out.println("Connected database successfully...");
  20. stmt = conn.createStatement();
  21. stmt.execute("SELECT * FROM `test`.`phonebook`");
  22. ResultSet rs = stmt.getResultSet();
  23. while (rs.next()){
  24. stmt.execute("DELETE FROM `test`.`phonebook` WHERE `Name`='" + rs.getString("Name") + "'");
  25. }
  26. Set<String> keys = phoneBook.keySet();
  27. for(String key: keys){
  28. stmt.execute("INSERT INTO `test`.`phonebook` (`Name`, `Number`) VALUES ('" +key+"','"+phoneBook.get(key)+"')");
  29. }
  30. }catch (SQLException se) {
  31. //Handle errors for JDBC
  32. se.printStackTrace();
  33. } catch (Exception e) {
  34. //Handle errors for Class.forName
  35. e.printStackTrace();
  36. } finally{
  37. try {
  38. if (stmt != null) {
  39. conn.close();
  40. }
  41. } catch (SQLException se) {
  42.  
  43. }
  44. try {
  45. if (conn != null) {
  46. conn.close();
  47. }
  48. } catch (SQLException se) {
  49. se.printStackTrace();
  50. }
  51. }
  52. }
  53. public void restored(){
  54. Connection conn = null;
  55. Statement stmt = null;
  56. try {
  57. Class.forName(dbClassName);
  58. // System.out.println("Connecting to a selected database...");
  59. conn = DriverManager.getConnection(CONNECTION, USER, PASS);
  60. // System.out.println("Connected database successfully...");
  61. stmt = conn.createStatement();
  62. stmt.execute("SELECT * FROM `test`.`phonebook`");
  63. ResultSet rs = stmt.getResultSet();
  64. while (rs.next()) {
  65. phoneBook.put(rs.getString("Name"), rs.getString("Number"));
  66. }
  67. }catch (SQLException se) {
  68. //Handle errors for JDBC
  69. se.printStackTrace();
  70. } catch (Exception e) {
  71. //Handle errors for Class.forName
  72. e.printStackTrace();
  73. } finally{
  74. try {
  75. if (stmt != null) {
  76. conn.close();
  77. }
  78. } catch (SQLException se) {
  79.  
  80. }
  81. try {
  82. if (conn != null) {
  83. conn.close();
  84. }
  85. } catch (SQLException se) {
  86. se.printStackTrace();
  87. }
  88. }
  89. }
  90. }
Add Comment
Please, Sign In to add comment